pool

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrClosed        = errors.New("fastworker: pool closed")
	ErrTerminated    = errors.New("fastworker: pool terminated")
	ErrPaused        = errors.New("fastworker: pool paused")
	ErrQueueFull     = errors.New("fastworker: queue full")
	ErrTimeout       = errors.New("fastworker: timeout")
	ErrCancelled     = errors.New("fastworker: cancelled")
	ErrDuplicate     = errors.New("fastworker: duplicate job")
	ErrRateLimited   = errors.New("fastworker: rate limited")
	ErrInvalidConfig = errors.New("fastworker: invalid config")
	ErrPermanent     = errors.New("fastworker: permanent error")
)

Functions

func HTTPMiddleware

func HTTPMiddleware(p *Pool, opt HTTPOptions) http.Handler

func IsPermanent

func IsPermanent(err error) bool

func IsRetryable

func IsRetryable(err error) bool

func MetadataFromContext

func MetadataFromContext(ctx context.Context) map[string]string

func MustShutdown

func MustShutdown(p *Pool, timeout time.Duration)

func Permanent

func Permanent(err error) error

func ReportProgress

func ReportProgress(ctx context.Context, percent int, message string)

func Retryable

func Retryable(err error) error

func RunUntilSignal

func RunUntilSignal(p *Pool) error

func ShutdownOnSignal

func ShutdownOnSignal(p *Pool, timeout time.Duration, sigs ...os.Signal) error

Application integration.

func SubmitChannel

func SubmitChannel[T any](p *Pool, ctx context.Context, ch <-chan T, h func(context.Context, T) error, opts ...JobOptions) error

func SubmitTask

func SubmitTask[T any](p *Pool, arg *T, fn TaskFunc[T], opts ...JobOptions) error

SubmitTask submits stateful work without allocating a capturing closure.

func SubmitTaskFast

func SubmitTaskFast[T any](p *Pool, arg *T, fn TaskFunc[T]) error

SubmitTaskFast submits stateful work through the minimal hot path.

Types

type AdminServer

type AdminServer struct {
	Pool  *Pool
	Token string
}

func (AdminServer) Handler

func (a AdminServer) Handler() http.Handler

func (AdminServer) ListenAndServe

func (a AdminServer) ListenAndServe(addr string) *http.Server

func (AdminServer) Shutdown

func (a AdminServer) Shutdown(ctx context.Context, srv *http.Server) error

type AnyHandler

type AnyHandler func(context.Context, any) error

AnyHandler can process arbitrary request payloads accepted by SubmitAny.

type AnyJob

type AnyJob struct {
	Payload any
	Handler AnyHandler
}

AnyJob adapts an arbitrary payload and handler into a Job.

func (AnyJob) Run

func (j AnyJob) Run(ctx context.Context) error

type Backoff

type Backoff interface {
	Delay(attempt int) time.Duration
}

type BackpressurePolicy

type BackpressurePolicy uint8
const (
	BackpressureBlock BackpressurePolicy = iota
	BackpressureReject
	BackpressureDropOldest
	BackpressureDropNewest
)

type BatchResult

type BatchResult[T any] struct {
	Values []T
	Errors []error
}

func Map

func Map[I any, O any](ctx context.Context, p *Pool, items []I, fn func(context.Context, I) (O, error), opts ...JobOptions) (BatchResult[O], error)

type Callback

type Callback struct {
	OnQueued     func(context.Context, JobInfo)
	OnStart      func(context.Context, JobInfo)
	OnSuccess    func(context.Context, JobInfo)
	OnError      func(context.Context, JobInfo, error)
	OnRetry      func(context.Context, JobInfo, int, error)
	OnDeadLetter func(context.Context, JobInfo, error)
	OnCancel     func(context.Context, JobInfo)
	OnPanic      func(context.Context, JobInfo, any)
	OnProgress   func(context.Context, JobInfo, Progress)
	OnFinally    func(context.Context, JobInfo, error)
}

type ChainBuilder

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

func (*ChainBuilder) Options

func (c *ChainBuilder) Options(opt JobOptions) *ChainBuilder

func (*ChainBuilder) Submit

func (c *ChainBuilder) Submit(ctx context.Context) error

func (*ChainBuilder) Then

func (c *ChainBuilder) Then(job Job) *ChainBuilder

func (*ChainBuilder) ThenFunc

func (c *ChainBuilder) ThenFunc(fn func(context.Context) error) *ChainBuilder

type Config

type Config struct {
	Name                  string
	MinWorkers            int
	MaxWorkers            int
	QueueSize             int
	Backpressure          BackpressurePolicy
	SubmitTimeout         time.Duration
	IdleTimeout           time.Duration
	ScaleInterval         time.Duration
	EnableAutoScale       bool
	RecoverPanics         bool
	DefaultTimeout        time.Duration
	DefaultMaxAttempts    int
	DefaultBackoff        Backoff
	MetricsSampleInterval time.Duration
	// EnableJobTracking stores queued/running jobs in an inspection map and auto-generates IDs.
	// It is disabled by default to keep the submit/execute hot path allocation-light.
	EnableJobTracking bool
	// EnableJobIDs generates job IDs even when tracking is disabled. Disabled by default.
	EnableJobIDs bool
	// DisableStats removes atomic counter updates from the submit/run hot path.
	// Use this for ultra-low-latency in-process execution where Stats() are not needed.
	DisableStats bool
}

func DefaultConfig

func DefaultConfig() Config

type ConstantBackoff

type ConstantBackoff time.Duration

func (ConstantBackoff) Delay

func (b ConstantBackoff) Delay(int) time.Duration

type Diagnosis

type Diagnosis struct {
	Healthy         bool   `json:"healthy"`
	Saturated       bool   `json:"saturated"`
	State           string `json:"state"`
	QueueDepth      int    `json:"queue_depth"`
	QueueCapacity   int    `json:"queue_capacity"`
	Workers         int    `json:"workers"`
	BusyWorkers     int    `json:"busy_workers"`
	OldestQueuedAge string `json:"oldest_queued_age,omitempty"`
	Recommendation  string `json:"recommendation,omitempty"`
}

Diagnostics.

type Event

type Event struct {
	Type      EventType         `json:"type"`
	Time      time.Time         `json:"time"`
	Pool      string            `json:"pool,omitempty"`
	State     string            `json:"state,omitempty"`
	Queue     string            `json:"queue,omitempty"`
	WorkerID  int               `json:"worker_id,omitempty"`
	Job       JobInfo           `json:"job,omitempty"`
	Options   JobOptions        `json:"-"`
	Attempt   int               `json:"attempt,omitempty"`
	Duration  time.Duration     `json:"duration,omitempty"`
	Error     error             `json:"-"`
	ErrorText string            `json:"error,omitempty"`
	Panic     any               `json:"-"`
	Message   string            `json:"message,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

Event is emitted for pool, worker, queue and job lifecycle transitions.

type EventType

type EventType string

EventType describes a lifecycle transition emitted by the pool. The values are stable strings so users can log, audit, filter and expose them directly.

const (
	EventPoolCreated     EventType = "pool.created"
	EventPoolStarting    EventType = "pool.starting"
	EventPoolStarted     EventType = "pool.started"
	EventPoolPausing     EventType = "pool.pausing"
	EventPoolPaused      EventType = "pool.paused"
	EventPoolResuming    EventType = "pool.resuming"
	EventPoolResumed     EventType = "pool.resumed"
	EventPoolStopping    EventType = "pool.stopping"
	EventPoolStopped     EventType = "pool.stopped"
	EventPoolTerminating EventType = "pool.terminating"
	EventPoolTerminated  EventType = "pool.terminated"
	EventDrainStarted    EventType = "drain.started"
	EventDrainCompleted  EventType = "drain.completed"

	EventQueuePaused  EventType = "queue.paused"
	EventQueueResumed EventType = "queue.resumed"
	EventQueueFull    EventType = "queue.full"
	EventQueueSpill   EventType = "queue.spill"

	EventWorkerStarting EventType = "worker.starting"
	EventWorkerStarted  EventType = "worker.started"
	EventWorkerStopping EventType = "worker.stopping"
	EventWorkerStopped  EventType = "worker.stopped"
	EventWorkerIdle     EventType = "worker.idle"

	EventJobSubmitting         EventType = "job.submitting"
	EventJobSubmitted          EventType = "job.submitted"
	EventJobAccepted           EventType = "job.accepted"
	EventJobRejected           EventType = "job.rejected"
	EventJobQueued             EventType = "job.queued"
	EventJobDequeued           EventType = "job.dequeued"
	EventJobStarting           EventType = "job.starting"
	EventJobStarted            EventType = "job.started"
	EventJobSucceeded          EventType = "job.succeeded"
	EventJobFailed             EventType = "job.failed"
	EventJobRetrying           EventType = "job.retrying"
	EventJobRetried            EventType = "job.retried"
	EventJobDeadLettered       EventType = "job.dead_lettered"
	EventJobCancelled          EventType = "job.cancelled"
	EventJobProgress           EventType = "job.progress"
	EventJobPanic              EventType = "job.panic"
	EventJobTimeout            EventType = "job.timeout"
	EventJobRateDelayed        EventType = "job.rate_delayed"
	EventJobConcurrencyDelayed EventType = "job.concurrency_delayed"

	EventHookPanic EventType = "hook.panic"
)

type ExponentialBackoff

type ExponentialBackoff struct {
	Initial, Max time.Duration
	Factor       float64
	Jitter       bool
}

func (ExponentialBackoff) Delay

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

type FileConfig

type FileConfig struct {
	Name    string `json:"name"`
	Workers struct {
		Min int `json:"min"`
		Max int `json:"max"`
	} `json:"workers"`
	Queue struct {
		Size         int    `json:"size"`
		Backpressure string `json:"backpressure"`
	} `json:"queue"`
	Tracking bool `json:"tracking"`
}

Config file support. JSON is fully supported; YAML supports simple key: value nesting used in README examples.

type FileStore

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

FileStore appends JSONL job state transitions and DLQ records. It is a simple, crash-safe audit store for production diagnostics and replay tooling. It does not serialize arbitrary Go function jobs for restart execution.

func NewFileStore

func NewFileStore(dir string) (*FileStore, error)

func (*FileStore) Close

func (f *FileStore) Close() error

func (*FileStore) SaveDeadLetter

func (f *FileStore) SaveDeadLetter(ctx context.Context, info JobInfo) error

func (*FileStore) SaveJob

func (f *FileStore) SaveJob(ctx context.Context, info JobInfo) error

type Future

type Future[T any] interface {
	Get(context.Context) (T, error)
	Done() <-chan struct{}
	Cancel() bool
}

func SubmitResult

func SubmitResult[T any](p *Pool, fn func(context.Context) (T, error), opts ...JobOptions) (Future[T], error)

type Group

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

func (*Group) Go

func (g *Group) Go(p *Pool, fn func(context.Context) error, opts ...JobOptions) error

func (*Group) Wait

func (g *Group) Wait() []error

type HTTPOptions

type HTTPOptions struct {
	Queue          string
	AcceptedCode   int
	MaxBodySize    int64
	CaptureHeaders []string
	RateLimitKey   string
	Timeout        time.Duration
	MaxAttempts    int
	RespondJobID   bool
	Handler        func(context.Context, HTTPRequest) error
}

HTTP async adapter.

type HTTPRequest

type HTTPRequest struct {
	Method     string      `json:"method"`
	URL        string      `json:"url"`
	Header     http.Header `json:"header,omitempty"`
	Body       []byte      `json:"body,omitempty"`
	RemoteAddr string      `json:"remote_addr,omitempty"`
	ReceivedAt time.Time   `json:"received_at"`
}

type Handler

type Handler[I any, O any] func(context.Context, I) (O, error)

type Hooks

type Hooks struct {
	OnPoolStart     func(*Pool)
	OnPoolStop      func(*Pool)
	OnWorkerStart   func(workerID int)
	OnWorkerStop    func(workerID int)
	OnJobSubmit     func(JobOptions)
	OnJobStart      func(context.Context, JobOptions, int)
	OnJobSuccess    func(context.Context, JobOptions, int)
	OnJobError      func(context.Context, JobOptions, int, error)
	OnJobPanic      func(context.Context, JobOptions, int, any)
	OnJobRetry      func(JobOptions, int, error)
	OnJobDeadLetter func(JobOptions, int, error)
}

type Job

type Job interface{ Run(context.Context) error }

func Chain

func Chain(job Job, m ...Middleware) Job

type JobBuilder

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

Job builder.

func (*JobBuilder) At

func (b *JobBuilder) At(t time.Time) *JobBuilder

func (*JobBuilder) Backoff

func (b *JobBuilder) Backoff(v Backoff) *JobBuilder

func (*JobBuilder) Callback

func (b *JobBuilder) Callback(cb *Callback) *JobBuilder

func (*JobBuilder) ConcurrencyKey

func (b *JobBuilder) ConcurrencyKey(k string, max int) *JobBuilder

func (*JobBuilder) Delay

func (b *JobBuilder) Delay(d time.Duration) *JobBuilder

func (*JobBuilder) ID

func (b *JobBuilder) ID(id string) *JobBuilder

func (*JobBuilder) IdempotencyKey

func (b *JobBuilder) IdempotencyKey(k string) *JobBuilder

func (*JobBuilder) Metadata

func (b *JobBuilder) Metadata(k, v string) *JobBuilder

func (*JobBuilder) Priority

func (b *JobBuilder) Priority(v Priority) *JobBuilder

func (*JobBuilder) Queue

func (b *JobBuilder) Queue(name string) *JobBuilder

func (*JobBuilder) RateLimit

func (b *JobBuilder) RateLimit(k string) *JobBuilder

func (*JobBuilder) Retry

func (b *JobBuilder) Retry(n int) *JobBuilder

func (*JobBuilder) Submit

func (b *JobBuilder) Submit(ctx context.Context) error

func (*JobBuilder) Timeout

func (b *JobBuilder) Timeout(d time.Duration) *JobBuilder

type JobFunc

type JobFunc func(context.Context) error

func (JobFunc) Run

func (fn JobFunc) Run(ctx context.Context) error

type JobInfo

type JobInfo struct {
	ID          string            `json:"id"`
	Queue       string            `json:"queue,omitempty"`
	State       string            `json:"state"`
	Priority    Priority          `json:"priority"`
	Attempts    int               `json:"attempts"`
	MaxAttempts int               `json:"max_attempts"`
	CreatedAt   time.Time         `json:"created_at"`
	RunAt       time.Time         `json:"run_at"`
	StartedAt   time.Time         `json:"started_at,omitempty"`
	FinishedAt  time.Time         `json:"finished_at,omitempty"`
	LastError   string            `json:"last_error,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	Progress    Progress          `json:"progress,omitempty"`
}

type JobOptions

type JobOptions struct {
	ID                  string
	Queue               string
	Priority            Priority
	Delay               time.Duration
	RunAt               time.Time
	Timeout             time.Duration
	MaxAttempts         int
	Backoff             Backoff
	Metadata            map[string]string
	IdempotencyKey      string
	ConcurrencyKey      string
	MaxConcurrentPerKey int
	RateLimitKey        string
	Result              any
	Callback            *Callback
	LifecycleMetadata   map[string]string
}

type JobState

type JobState uint32
const (
	JobQueued JobState = iota
	JobRunning
	JobSucceeded
	JobFailed
	JobRetrying
	JobDeadLettered
	JobCancelled
)

func (JobState) String

func (s JobState) String() string

type Lifecycle

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

Lifecycle is a small safe event bus. It is disabled unless configured, so the hot path remains allocation-light for benchmark/low-latency mode.

func NewLifecycle

func NewLifecycle() *Lifecycle

func (*Lifecycle) On

func (l *Lifecycle) On(fn LifecycleHandler, types ...EventType) func()

On registers a handler for one or more event types. With no types it receives all events. It returns an unsubscribe function.

func (*Lifecycle) RecoveredPanics

func (l *Lifecycle) RecoveredPanics() uint64

func (*Lifecycle) SetAsync

func (l *Lifecycle) SetAsync(v bool)

type LifecycleHandler

type LifecycleHandler func(context.Context, Event)

LifecycleHandler receives lifecycle events. Handlers must be fast. For slow operations use Lifecycle.SetAsync(true) or enqueue work into another system.

type Middleware

type Middleware func(Job) Job

func Logger

func Logger(prefix string) Middleware

Logger records duration and final error using the standard logger.

func Timeout

func Timeout(d time.Duration) Middleware

Timeout wraps each job with a context timeout. JobOptions.Timeout is usually preferred for per-job deadlines, but middleware is useful for global policy.

func WithMetadata

func WithMetadata(md map[string]string) Middleware

type Option

type Option func(*Pool)

func PresetAPIBuffer

func PresetAPIBuffer() Option

func PresetBackgroundQueue

func PresetBackgroundQueue() Option

func PresetHighThroughput

func PresetHighThroughput() Option

func PresetLowLatency

func PresetLowLatency() Option

Presets.

func PresetReliable

func PresetReliable() Option

func WithAsyncLifecycle

func WithAsyncLifecycle(enabled bool) Option

func WithAutoScale

func WithAutoScale(enabled bool) Option

func WithBackpressure

func WithBackpressure(b BackpressurePolicy) Option

func WithDefaultOptions

func WithDefaultOptions(opt JobOptions) Option

func WithHooks

func WithHooks(h Hooks) Option

func WithJobIDs

func WithJobIDs(enabled bool) Option

func WithJobTracking

func WithJobTracking(enabled bool) Option

func WithLifecycle

func WithLifecycle(l *Lifecycle) Option

func WithLifecycleHook

func WithLifecycleHook(fn LifecycleHandler, types ...EventType) Option

func WithMiddleware

func WithMiddleware(m ...Middleware) Option

func WithName

func WithName(name string) Option

func WithQueuePolicy

func WithQueuePolicy(name string, policy QueuePolicy) Option

func WithQueueSize

func WithQueueSize(n int) Option

func WithRateLimit

func WithRateLimit(key string, r RateLimit) Option

func WithRecoverPanics

func WithRecoverPanics(enabled bool) Option

func WithSpillover

func WithSpillover(dir string, maxJobs int) Option

func WithStore

func WithStore(s Store) Option

func WithSubmitTimeout

func WithSubmitTimeout(d time.Duration) Option

func WithWorkerClose

func WithWorkerClose(fn WorkerCloseFunc) Option

func WithWorkerInit

func WithWorkerInit(fn WorkerInitFunc) Option

func WithWorkerRange

func WithWorkerRange(min, max int) Option

func WithWorkers

func WithWorkers(n int) Option

type PermanentError

type PermanentError struct{ Err error }

func (PermanentError) Error

func (e PermanentError) Error() string

func (PermanentError) Unwrap

func (e PermanentError) Unwrap() error

type Pool

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

func FromConfigFile

func FromConfigFile(path string, opts ...Option) (*Pool, error)

func MustNew

func MustNew(c Config, opts ...Option) *Pool

func MustNewPool

func MustNewPool(opts ...Option) *Pool

func New

func New(c Config, opts ...Option) (*Pool, error)

func NewPool

func NewPool(opts ...Option) (*Pool, error)

Functional options for ergonomic construction.

func (*Pool) ActiveJobs

func (p *Pool) ActiveJobs() []JobInfo

func (*Pool) CancelAll

func (p *Pool) CancelAll(ctx context.Context) int

func (*Pool) CancelJob

func (p *Pool) CancelJob(id string) bool

CancelJob cancels a queued or running job by ID. Queued jobs are skipped when a worker reaches them; running jobs receive context cancellation.

func (*Pool) Chain

func (p *Pool) Chain() *ChainBuilder

func (*Pool) DeadLetters

func (p *Pool) DeadLetters() []JobOptions

func (*Pool) Diagnose

func (p *Pool) Diagnose() Diagnosis

func (*Pool) Drain

func (p *Pool) Drain(ctx context.Context) error

Drain rejects new jobs by entering stopping state, waits for all accepted jobs to finish, and then leaves the pool stopped. It is equivalent to a graceful Stop but named for operational clarity.

func (*Pool) Dump

func (p *Pool) Dump() string

func (*Pool) ExplainSaturation

func (p *Pool) ExplainSaturation() string

func (*Pool) InspectJob

func (p *Pool) InspectJob(id string) (JobInfo, bool)

InspectJob returns a snapshot of a queued/running/recent job when it is still tracked by the pool. Completed successful jobs are removed from the hot index to avoid unbounded memory growth.

func (*Pool) IsPaused

func (p *Pool) IsPaused() bool

func (*Pool) IsQueuePaused

func (p *Pool) IsQueuePaused(name string) bool

func (*Pool) IsRunning

func (p *Pool) IsRunning() bool

func (*Pool) Job

func (p *Pool) Job(job Job) *JobBuilder

func (*Pool) JobFunc

func (p *Pool) JobFunc(fn func(context.Context) error) *JobBuilder

func (*Pool) JoinExisting

func (p *Pool) JoinExisting(key string, job Job, opts ...JobOptions) error

func (*Pool) Lifecycle

func (p *Pool) Lifecycle() *Lifecycle

func (*Pool) On

func (p *Pool) On(fn LifecycleHandler, types ...EventType) func()

func (*Pool) Once

func (p *Pool) Once(key string, job Job, opts ...JobOptions) error

Idempotency conveniences.

func (*Pool) OncePer

func (p *Pool) OncePer(key string, ttl time.Duration, job Job, opts ...JobOptions) error

func (*Pool) Pause

func (p *Pool) Pause() error

func (*Pool) PauseQueue

func (p *Pool) PauseQueue(name string)

func (*Pool) Prometheus

func (p *Pool) Prometheus() string

func (*Pool) PurgeDeadLetters

func (p *Pool) PurgeDeadLetters() int

PurgeDeadLetters clears the in-memory DLQ and returns the number of removed jobs.

func (*Pool) Queue

func (p *Pool) Queue(name string) QueueHandle

Queue returns a named queue handle. The handle is cheap and can be kept by callers.

func (*Pool) QueueDepth

func (p *Pool) QueueDepth() int

func (*Pool) QueuePolicy

func (p *Pool) QueuePolicy(name string) (QueuePolicy, bool)

func (*Pool) Replace

func (p *Pool) Replace(key string, job Job, opts ...JobOptions) error

func (*Pool) ReplayDeadLetters

func (p *Pool) ReplayDeadLetters() (int, error)

ReplayDeadLetters re-enqueues all currently captured dead-lettered jobs and returns the number accepted. Jobs keep their original options but attempts are reset. The in-memory DLQ is cleared only for successfully requeued jobs.

func (*Pool) Resize

func (p *Pool) Resize(workers int)

func (*Pool) Resume

func (p *Pool) Resume() error

func (*Pool) ResumeQueue

func (p *Pool) ResumeQueue(name string)

func (*Pool) ScheduleAfter

func (p *Pool) ScheduleAfter(id string, after time.Duration, job Job, opts ...JobOptions) error

func (*Pool) ScheduleAt

func (p *Pool) ScheduleAt(id string, at time.Time, job Job, opts ...JobOptions) error

func (*Pool) ScheduleCron

func (p *Pool) ScheduleCron(id, expr string, job Job, opts ...JobOptions) (ScheduleHandle, error)

ScheduleCron supports @every <duration> and compact step expressions such as "*/5 * * * * *" (every five seconds) or "*/2 * * * *" (every two minutes). It intentionally avoids third-party dependencies while covering common worker scheduling use cases.

func (*Pool) ScheduleEvery

func (p *Pool) ScheduleEvery(id string, every time.Duration, job Job, opts ...JobOptions) ScheduleHandle

func (*Pool) SetDefaultOptions

func (p *Pool) SetDefaultOptions(opt JobOptions)

func (*Pool) SetQueuePolicy

func (p *Pool) SetQueuePolicy(name string, policy QueuePolicy)

SetQueuePolicy updates defaults applied to jobs submitted with opts.Queue/name.

func (*Pool) SetRateLimit

func (p *Pool) SetRateLimit(key string, r RateLimit)

func (*Pool) Shutdown

func (p *Pool) Shutdown(ctx context.Context) error

func (*Pool) SpillDepth

func (p *Pool) SpillDepth() int

func (*Pool) Start

func (p *Pool) Start() error

func (*Pool) State

func (p *Pool) State() State

func (*Pool) Stats

func (p *Pool) Stats() Stats

func (*Pool) Stop

func (p *Pool) Stop(ctx context.Context) error

func (*Pool) Submit

func (p *Pool) Submit(job Job, opts ...JobOptions) error

func (*Pool) SubmitAny

func (p *Pool) SubmitAny(payload any, handler AnyHandler, opts ...JobOptions) error

SubmitAny accepts any request/payload type and queues it for background processing by handler. It is useful for HTTP/event ingestion where admission should be fast while workers handle smoothing, rate limits and concurrency.

func (*Pool) SubmitBytes

func (p *Pool) SubmitBytes(data []byte, h func(context.Context, []byte) error, opts ...JobOptions) error

Request adapters.

func (*Pool) SubmitFast

func (p *Pool) SubmitFast(job Job) error

SubmitFast is the minimal zero-allocation hot path for immediate jobs. It intentionally bypasses options, hooks, middleware, tracking, retries, rate limiting, idempotency, and stats. Use Submit for the full-featured path.

func (*Pool) SubmitFunc

func (p *Pool) SubmitFunc(fn func(context.Context) error, opts ...JobOptions) error

func (*Pool) SubmitJSON

func (p *Pool) SubmitJSON(data []byte, dst any, h func(context.Context, any) error, opts ...JobOptions) error

func (*Pool) SubmitMap

func (p *Pool) SubmitMap(m map[string]any, h func(context.Context, map[string]any) error, opts ...JobOptions) error

func (*Pool) SubmitResult

func (p *Pool) SubmitResult(fn func(context.Context) (any, error), opts ...JobOptions) (Future[any], error)

func (*Pool) SubmitStruct

func (p *Pool) SubmitStruct(v any, h func(context.Context, any) error, opts ...JobOptions) error

func (*Pool) SubmitTask

func (p *Pool) SubmitTask(arg any, fn func(context.Context, any) error, opts ...JobOptions) error

SubmitTask submits stateful work without allocating a capturing closure.

func (*Pool) Terminate

func (p *Pool) Terminate() error

func (*Pool) UpdateQueueWeight

func (p *Pool) UpdateQueueWeight(name string, priority Priority)

func (*Pool) UpdateRateLimit

func (p *Pool) UpdateRateLimit(key string, r RateLimit)

Runtime reconfiguration.

func (*Pool) Wait

func (p *Pool) Wait(ctx context.Context) error

Wait waits for all worker goroutines to exit. It is useful after Terminate.

func (*Pool) WaitIdle

func (p *Pool) WaitIdle(ctx context.Context) error

WaitIdle waits until the queue is empty and no worker is executing a job. It does not stop the pool.

func (*Pool) WhenAll

func (p *Pool) WhenAll(jobs ...Job) *WhenAllBuilder

func (*Pool) WorkerCount

func (p *Pool) WorkerCount() int

type Priority

type Priority int
const (
	PriorityLow      Priority = -10
	PriorityNormal   Priority = 0
	PriorityHigh     Priority = 10
	PriorityCritical Priority = 100
)

type Progress

type Progress struct {
	Percent int    `json:"percent,omitempty"`
	Message string `json:"message,omitempty"`
}

type QueueHandle

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

func (QueueHandle) Pause

func (q QueueHandle) Pause()

func (QueueHandle) Resume

func (q QueueHandle) Resume()

func (QueueHandle) Submit

func (q QueueHandle) Submit(job Job, opts ...JobOptions) error

func (QueueHandle) SubmitAny

func (q QueueHandle) SubmitAny(payload any, h AnyHandler, opts ...JobOptions) error

func (QueueHandle) SubmitFunc

func (q QueueHandle) SubmitFunc(fn func(context.Context) error, opts ...JobOptions) error

func (QueueHandle) SubmitResult

func (q QueueHandle) SubmitResult(fn func(context.Context) (any, error), opts ...JobOptions) (Future[any], error)

type QueuePolicy

type QueuePolicy struct {
	Name                string
	Priority            Priority
	Timeout             time.Duration
	MaxAttempts         int
	Backoff             Backoff
	RateLimitKey        string
	ConcurrencyKey      string
	MaxConcurrentPerKey int
	Metadata            map[string]string
}

QueuePolicy defines ergonomic per-queue defaults. It intentionally maps to JobOptions so queue groups can stay allocation-light and share the same pool.

type RateLimit

type RateLimit struct {
	// Rate is tokens per second. Values <= 0 disable the limiter for the key.
	Rate int
	// Burst is the immediate burst size. Values <= 0 default to Rate.
	Burst int
	// Mode controls admission behavior. Zero value RateLimitQueue accepts and smooths.
	Mode RateLimitMode
}

type RateLimitMode

type RateLimitMode uint8
const (
	// RateLimitQueue accepts the job and smooths execution in the background.
	// This is the default and is the recommended mode for request buffering.
	RateLimitQueue RateLimitMode = iota
	// RateLimitReject preserves traditional limiter behavior: Submit returns ErrRateLimited.
	RateLimitReject
	// RateLimitBlock waits during Submit until a token is available. Use carefully.
	RateLimitBlock
)

type RetryableError

type RetryableError struct{ Err error }

func (RetryableError) Error

func (e RetryableError) Error() string

func (RetryableError) Unwrap

func (e RetryableError) Unwrap() error

type ScheduleHandle

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

func (ScheduleHandle) Cancel

func (h ScheduleHandle) Cancel()

func (ScheduleHandle) Done

func (h ScheduleHandle) Done() <-chan struct{}

type State

type State uint32

func (State) String

func (s State) String() string

type Stats

type Stats struct {
	Submitted, Accepted, Rejected, Started, Completed, Failed, Retried, Panicked, TimedOut, DeadLettered, RateDelayed uint64
	QueueDepth                                                                                                        int
	Workers                                                                                                           int
	BusyWorkers                                                                                                       int
	Paused                                                                                                            bool
	Stopped                                                                                                           bool
	Terminated                                                                                                        bool
	Uptime                                                                                                            time.Duration
}

type Store

type Store interface {
	SaveJob(context.Context, JobInfo) error
	SaveDeadLetter(context.Context, JobInfo) error
	Close() error
}

Store records job state transitions and dead-letter events. It is intentionally tiny so production users can plug in file, database, Redis, NATS, Kafka, or custom audit backends without affecting the hot path when disabled.

type Task

type Task[T any] struct {
	Arg *T
	Fn  TaskFunc[T]
}

Task is a small value-type Job. Passing Task[T] to Submit/SubmitFast avoids closure heap allocation while still carrying state through Arg.

func (Task[T]) Run

func (t Task[T]) Run(ctx context.Context) error

type TaskFunc

type TaskFunc[T any] func(context.Context, *T) error

TaskFunc processes a reusable argument without creating a per-submit closure. It is the zero-allocation alternative to SubmitFunc when the work needs state.

type TestPool

type TestPool struct{ *Pool }

Testing helpers.

func NewTestPool

func NewTestPool() *TestPool

func (*TestPool) RunAll

func (t *TestPool) RunAll(ctx context.Context) error

func (*TestPool) WaitForJobs

func (t *TestPool) WaitForJobs(ctx context.Context, n uint64) error

type TypedPool

type TypedPool[I any, O any] struct {
	// contains filtered or unexported fields
}

func MustNewTyped

func MustNewTyped[I any, O any](cfg Config, h Handler[I, O], opts ...Option) *TypedPool[I, O]

func NewTyped

func NewTyped[I any, O any](cfg Config, h Handler[I, O], opts ...Option) (*TypedPool[I, O], error)

func (*TypedPool[I, O]) Pause

func (t *TypedPool[I, O]) Pause() error

func (*TypedPool[I, O]) Pool

func (t *TypedPool[I, O]) Pool() *Pool

func (*TypedPool[I, O]) Resume

func (t *TypedPool[I, O]) Resume() error

func (*TypedPool[I, O]) Start

func (t *TypedPool[I, O]) Start() error

func (*TypedPool[I, O]) Stats

func (t *TypedPool[I, O]) Stats() Stats

func (*TypedPool[I, O]) Stop

func (t *TypedPool[I, O]) Stop(ctx context.Context) error

func (*TypedPool[I, O]) Submit

func (t *TypedPool[I, O]) Submit(ctx context.Context, in I, opts ...JobOptions) (Future[O], error)

func (*TypedPool[I, O]) Terminate

func (t *TypedPool[I, O]) Terminate() error

type WhenAllBuilder

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

func (*WhenAllBuilder) Options

func (w *WhenAllBuilder) Options(opt JobOptions) *WhenAllBuilder

func (*WhenAllBuilder) Submit

func (w *WhenAllBuilder) Submit(ctx context.Context) error

func (*WhenAllBuilder) Then

func (w *WhenAllBuilder) Then(job Job) *WhenAllBuilder

func (*WhenAllBuilder) ThenFunc

func (w *WhenAllBuilder) ThenFunc(fn func(context.Context) error) *WhenAllBuilder

type Worker

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

func (*Worker) Get

func (w *Worker) Get(key string) (any, bool)

func (*Worker) Set

func (w *Worker) Set(key string, value any)

type WorkerCloseFunc

type WorkerCloseFunc func(context.Context, *Worker) error

type WorkerInitFunc

type WorkerInitFunc func(context.Context, *Worker) error

Worker local state.

Jump to

Keyboard shortcuts

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