Documentation
¶
Overview ¶
Package kyu is an importable distributed job queue library backed by PostgreSQL (persistence) and Redis (queue/priority sorted-set).
Index ¶
- type Config
- type EnqueueOptions
- type EnqueueRequest
- type JobFilter
- type Middleware
- type Queue
- func (q *Queue) CancelJob(ctx context.Context, id string) error
- func (q *Queue) Connect(ctx context.Context) error
- func (q *Queue) DeadJobs(ctx context.Context) ([]kyudb.Job, error)
- func (q *Queue) Delete(ctx context.Context, id string) error
- func (q *Queue) DeleteDead(ctx context.Context, id string) error
- func (q *Queue) Enqueue(ctx context.Context, jobType, payload string, opts EnqueueOptions) (string, error)
- func (q *Queue) EnqueueMany(ctx context.Context, jobs []EnqueueRequest) ([]string, error)
- func (q *Queue) Info() QueueInfo
- func (q *Queue) Inspect(ctx context.Context, id string) (kyudb.Job, error)
- func (q *Queue) InspectDead(ctx context.Context, id string) (kyudb.Job, error)
- func (q *Queue) IsPaused() bool
- func (q *Queue) JobTypes() []string
- func (q *Queue) ListDead(ctx context.Context) ([]kyudb.Job, error)
- func (q *Queue) ListJobs(ctx context.Context, filter JobFilter) ([]kyudb.Job, error)
- func (q *Queue) Pause()
- func (q *Queue) Ping(ctx context.Context) error
- func (q *Queue) Purge(ctx context.Context, status string) (int64, error)
- func (q *Queue) QueueName() string
- func (q *Queue) Register(jobType string, handler func(ctx context.Context, payload string) error)
- func (q *Queue) Reset(ctx context.Context, id string) error
- func (q *Queue) Resume()
- func (q *Queue) Retry(ctx context.Context, id string) error
- func (q *Queue) RetryAllDead(ctx context.Context, queue string) (int, error)
- func (q *Queue) RunOnce(ctx context.Context) error
- func (q *Queue) Start(ctx context.Context) error
- func (q *Queue) Stats(ctx context.Context) (QueueStats, error)
- func (q *Queue) Use(mw Middleware)
- func (q *Queue) WorkerCount() int
- func (q *Queue) Workers() []WorkerInfo
- type QueueInfo
- type QueueStats
- type WorkerInfo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// DSN is the PostgreSQL connection string.
// No default; must be provided.
DSN string
// RedisAddr is the Redis host:port address.
// Default: "localhost:6379"
RedisAddr string
// RedisPassword is the password for the Redis server.
// Default: ""
RedisPassword string
// Workers is the number of concurrent worker goroutines.
// Default: 5
Workers int
// MetricsPort is the port the Prometheus /metrics HTTP server listens on.
// Set to 0 to disable the metrics server.
// Default: 9090
MetricsPort int
// Logger is used for internal diagnostic messages.
// Defaults to the standard library logger when nil.
Logger *log.Logger
// StaleJobTimeout is the duration after which a running job is considered stale
// and can be retried by another worker.
// Default: 5 minutes
StaleJobTimeout time.Duration
// SchedulerInterval is how often the scheduler promotes scheduled and
// failed jobs whose time has arrived back into the queue.
// Default: 5 seconds
SchedulerInterval time.Duration
// ReaperInterval is how often the stale reaper scans for jobs stuck in
// the running state longer than StaleJobTimeout and resets them.
// Default: 1 minute
ReaperInterval time.Duration
// QueueName is the Redis key for the job queue.
// Default: "kyu:default"
QueueName string
// CallbackURL is an optional HTTP endpoint that kyu calls (POST with a
// JSON body containing job_id/status/payload) whenever a job completes.
// If empty, no callbacks are sent.
CallbackURL string
// MaxOpenConns is the maximum number of open database connections.
// Default: 25
MaxOpenConns int
// MaxIdleConns is the maximum number of idle database connections.
// Default: 25
MaxIdleConns int
// ConnMaxLifetime is the maximum lifetime of a database connection.
// Default: 5 minutes
ConnMaxLifetime time.Duration
// OrphanCheckInterval is how often the orphaned job checker runs to find
// pending jobs that were popped from Redis but never made it to the database.
// Default: 1 minute
OrphanCheckInterval time.Duration
// DisableAutoMigrate skips the embedded goose migrations that normally run
// on Connect. Set to true if you manage the kyu schema yourself (e.g. via
// your own migration tool against the same database).
// Default: false (migrations run automatically)
DisableAutoMigrate bool
}
Config holds all tunable parameters for a Queue. Zero-value fields fall back to sensible defaults applied by New.
type EnqueueOptions ¶
type EnqueueOptions struct {
// Priority is the job priority. Higher values indicate higher priority.
// Jobs with higher priority are processed before lower priority jobs.
// Default: 0
Priority int
// MaxRetries is the maximum number of times to retry a failed job.
// Default: 0 (no retries)
MaxRetries int
// ScheduledAt is the time at which the job should be executed.
// If nil or in the past, the job is enqueued immediately.
ScheduledAt *time.Time
// TimeOut is the maximum time the job handler can run before being cancelled.
// Default: 30 seconds
TimeOut *time.Duration
}
type EnqueueRequest ¶ added in v1.0.3
type EnqueueRequest struct {
// JobType is the registered job type to run.
JobType string
// Payload is the opaque payload passed to the job handler.
Payload string
// Options is the per-job enqueue configuration.
Options EnqueueOptions
}
EnqueueRequest describes a single job for batch enqueuing.
type JobFilter ¶ added in v1.0.3
type JobFilter struct {
// Status restricts to a single status: pending, running, completed,
// failed, scheduled, cancelled, or dead. Empty matches every status.
Status string
// JobType restricts to a single registered job type. Empty matches all.
JobType string
// Limit caps the number of returned jobs (most recent first). 0 = default 100.
Limit int
// Offset skips the first Offset matching jobs, enabling pagination.
// Combine with Limit to page through a long list. 0 = no offset.
Offset int
}
JobFilter filters job listings. Empty fields match anything; Limit <= 0 defaults to the 100 most recent matching jobs.
type Middleware ¶
Middleware is a function that wraps job execution. It receives the job context, type, payload, and a next function to call the handler. Use Middleware to add logging, metrics, or other cross-cutting concerns.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue is the main handle for the kyu job queue library. Create one with New, register handlers with Register, then call Start.
func New ¶
New creates a new Queue with the given configuration. Defaults are applied for any zero-value fields; see Config for details. New does NOT open any connections — that happens inside Connect and Start.
func (*Queue) CancelJob ¶
CancelJob cancels a pending, scheduled, or failed job by setting its status to cancelled.
func (*Queue) DeadJobs ¶
DeadJobs returns all jobs that have exhausted all retries and are marked as dead.
func (*Queue) Delete ¶ added in v1.0.3
Delete soft-deletes any job (of any status) by ID. It also removes the ID from the pending Redis set so it is never dispatched. Returns an error if the job does not exist. For dead-letter jobs specifically, see DeleteDead.
func (*Queue) DeleteDead ¶ added in v1.0.3
DeleteDead soft-deletes a single dead job (sets deleted_at) so it disappears from all listings. It returns an error if no dead job exists with the ID.
func (*Queue) Enqueue ¶
func (q *Queue) Enqueue(ctx context.Context, jobType, payload string, opts EnqueueOptions) (string, error)
Enqueue adds a new job to the queue.
func (*Queue) EnqueueMany ¶ added in v1.0.3
EnqueueMany batches job creation: all jobs are inserted into Postgres with a single COPY statement and pushed onto the Redis queue with a single ZADD. IDs are returned in the same order as the input. Like Enqueue, the Postgres insert happens first; if the Redis push then fails, the jobs stay persisted as pending and are recovered by the orphan reaper.
func (*Queue) InspectDead ¶ added in v1.0.3
InspectDead returns a single dead job by ID. It returns an error if no dead job exists with the given ID.
func (*Queue) IsPaused ¶ added in v1.0.3
IsPaused reports whether the worker pool is currently paused.
func (*Queue) JobTypes ¶ added in v1.0.3
JobTypes returns the sorted names of every registered job type.
func (*Queue) ListDead ¶ added in v1.0.3
ListDead returns all jobs currently in the dead state. It is an alias for DeadJobs kept for a friendlier name.
func (*Queue) ListJobs ¶ added in v1.0.3
ListJobs returns jobs matching the filter, most recent first. Use JobFilter.Limit and JobFilter.Offset to page through long lists.
func (*Queue) Pause ¶ added in v1.0.3
func (q *Queue) Pause()
Pause tells the worker pool to stop popping new jobs. In-flight jobs finish; queued jobs wait until Resume is called. Pause is per-process state - it only affects this Queue instance.
func (*Queue) Ping ¶ added in v1.0.3
Ping verifies that both PostgreSQL and Redis are reachable. Useful for health checks.
func (*Queue) Purge ¶ added in v1.0.3
Purge soft-deletes every job in the given status and returns how many rows were affected. Status must be one of: pending, running, completed, failed, scheduled, cancelled, dead.
func (*Queue) QueueName ¶ added in v1.0.3
QueueName returns the Redis sorted set key this queue processes.
func (*Queue) Register ¶
Register associates a handler function with a named job type. Register is safe to call concurrently and may be called before or after Start.
func (*Queue) Reset ¶ added in v1.0.3
Reset returns a failed or cancelled job to the pending state and re-enqueues it so it can be processed again. Dead jobs should use Retry instead. Returns an error if the job does not exist or is not in a resettable state.
func (*Queue) Resume ¶ added in v1.0.3
func (q *Queue) Resume()
Resume allows the worker pool to pop jobs again after a Pause.
func (*Queue) Retry ¶ added in v1.0.3
Retry moves a single dead job back into the pending state, clears its retry counter and error, and re-enqueues it on the queue so it can run again with a fresh set of retries. It returns an error if the job does not exist or is not dead.
func (*Queue) RetryAllDead ¶ added in v1.0.3
RetryAllDead resets every dead job back to pending, clears retry counters and errors, and re-enqueues them all on the given Redis queue. It returns the number of jobs retried.
func (*Queue) RunOnce ¶
RunOnce runs all registered workers once to process any pending jobs. It blocks until all workers complete. Call Connect() before RunOnce().
func (*Queue) Start ¶
Start blocks until the provided context is cancelled, at which point it performs a graceful shutdown and returns any accumulated error. If multiple subsystems fail, only the first error is returned.
func (*Queue) Stats ¶ added in v1.0.3
func (q *Queue) Stats(ctx context.Context) (QueueStats, error)
Stats returns a point-in-time snapshot of job counts and queue depth. See QueueStats for the exact semantics.
func (*Queue) Use ¶
func (q *Queue) Use(mw Middleware)
Use registers a middleware function to be called for every job execution.
func (*Queue) WorkerCount ¶ added in v1.0.3
WorkerCount returns the configured number of workers in the pool.
func (*Queue) Workers ¶ added in v1.0.3
func (q *Queue) Workers() []WorkerInfo
Workers returns a snapshot of the worker pool, one entry per configured worker, with its busy state.
type QueueInfo ¶ added in v1.0.3
type QueueInfo struct {
QueueName string `json:"queue_name"`
Workers int `json:"workers"`
MetricsPort int `json:"metrics_port"`
CallbackEnabled bool `json:"callback_enabled"`
StaleJobTimeout time.Duration `json:"stale_job_timeout"`
SchedulerInterval time.Duration `json:"scheduler_interval"`
ReaperInterval time.Duration `json:"reaper_interval"`
OrphanCheckInterval time.Duration `json:"orphan_check_interval"`
}
QueueInfo is a read-only summary of how this queue is configured.
type QueueStats ¶ added in v1.0.3
type QueueStats struct {
Pending int64 `json:"pending"`
Running int64 `json:"running"`
Completed int64 `json:"completed"`
Failed int64 `json:"failed"`
Scheduled int64 `json:"scheduled"`
Cancelled int64 `json:"cancelled"`
Dead int64 `json:"dead"`
Total int64 `json:"total"`
QueueDepth int64 `json:"queue_depth"`
}
QueueStats is a point-in-time snapshot of job counts. Because all kyu queues in a database share the same jobs table, the status counts are global to the database, while QueueDepth is the number of IDs waiting in this queue's Redis sorted set.
type WorkerInfo ¶ added in v1.0.3
type WorkerInfo struct {
// ID is the worker's stable identifier, e.g. "worker-3".
ID string `json:"id"`
// Busy is true while the worker is executing a job.
Busy bool `json:"busy"`
}
WorkerInfo describes one worker in this process's worker pool.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
example
command
Command example runs a self-contained, end-to-end kyu workflow that you can watch live on the web dashboard.
|
Command example runs a self-contained, end-to-end kyu workflow that you can watch live on the web dashboard. |
|
kyu
command
Command kyu is a small CLI for running and managing a kyu queue.
|
Command kyu is a small CLI for running and managing a kyu queue. |
|
Package dashboard embeds the kyu web UI and serves it next to a JSON API backed by a live kyu.Queue.
|
Package dashboard embeds the kyu web UI and serves it next to a JSON API backed by a live kyu.Queue. |
|
db
|
|
kyu jobs visualized on Grafana
