Documentation
¶
Index ¶
- Variables
- func HTTPMiddleware(p *Pool, opt HTTPOptions) http.Handler
- func IsPermanent(err error) bool
- func IsRetryable(err error) bool
- func MetadataFromContext(ctx context.Context) map[string]string
- func MustShutdown(p *Pool, timeout time.Duration)
- func Permanent(err error) error
- func ReportProgress(ctx context.Context, percent int, message string)
- func Retryable(err error) error
- func RunUntilSignal(p *Pool) error
- func ShutdownOnSignal(p *Pool, timeout time.Duration, sigs ...os.Signal) error
- func SubmitChannel[T any](p *Pool, ctx context.Context, ch <-chan T, h func(context.Context, T) error, ...) error
- func SubmitTask[T any](p *Pool, arg *T, fn TaskFunc[T], opts ...JobOptions) error
- func SubmitTaskFast[T any](p *Pool, arg *T, fn TaskFunc[T]) error
- type AdminServer
- type AnyHandler
- type AnyJob
- type Backoff
- type BackpressurePolicy
- type BatchResult
- type Callback
- type ChainBuilder
- type Config
- type ConstantBackoff
- type Diagnosis
- type Event
- type EventType
- type ExponentialBackoff
- type FileConfig
- type FileStore
- type Future
- type Group
- type HTTPOptions
- type HTTPRequest
- type Handler
- type Hooks
- type Job
- type JobBuilder
- func (b *JobBuilder) At(t time.Time) *JobBuilder
- func (b *JobBuilder) Backoff(v Backoff) *JobBuilder
- func (b *JobBuilder) Callback(cb *Callback) *JobBuilder
- func (b *JobBuilder) ConcurrencyKey(k string, max int) *JobBuilder
- func (b *JobBuilder) Delay(d time.Duration) *JobBuilder
- func (b *JobBuilder) ID(id string) *JobBuilder
- func (b *JobBuilder) IdempotencyKey(k string) *JobBuilder
- func (b *JobBuilder) Metadata(k, v string) *JobBuilder
- func (b *JobBuilder) Priority(v Priority) *JobBuilder
- func (b *JobBuilder) Queue(name string) *JobBuilder
- func (b *JobBuilder) RateLimit(k string) *JobBuilder
- func (b *JobBuilder) Retry(n int) *JobBuilder
- func (b *JobBuilder) Submit(ctx context.Context) error
- func (b *JobBuilder) Timeout(d time.Duration) *JobBuilder
- type JobFunc
- type JobInfo
- type JobOptions
- type JobState
- type Lifecycle
- type LifecycleHandler
- type Middleware
- type Option
- func PresetAPIBuffer() Option
- func PresetBackgroundQueue() Option
- func PresetHighThroughput() Option
- func PresetLowLatency() Option
- func PresetReliable() Option
- func WithAsyncLifecycle(enabled bool) Option
- func WithAutoScale(enabled bool) Option
- func WithBackpressure(b BackpressurePolicy) Option
- func WithDefaultOptions(opt JobOptions) Option
- func WithHooks(h Hooks) Option
- func WithJobIDs(enabled bool) Option
- func WithJobTracking(enabled bool) Option
- func WithLifecycle(l *Lifecycle) Option
- func WithLifecycleHook(fn LifecycleHandler, types ...EventType) Option
- func WithMiddleware(m ...Middleware) Option
- func WithName(name string) Option
- func WithQueuePolicy(name string, policy QueuePolicy) Option
- func WithQueueSize(n int) Option
- func WithRateLimit(key string, r RateLimit) Option
- func WithRecoverPanics(enabled bool) Option
- func WithSpillover(dir string, maxJobs int) Option
- func WithStore(s Store) Option
- func WithSubmitTimeout(d time.Duration) Option
- func WithWorkerClose(fn WorkerCloseFunc) Option
- func WithWorkerInit(fn WorkerInitFunc) Option
- func WithWorkerRange(min, max int) Option
- func WithWorkers(n int) Option
- type PermanentError
- type Pool
- func (p *Pool) ActiveJobs() []JobInfo
- func (p *Pool) CancelAll(ctx context.Context) int
- func (p *Pool) CancelJob(id string) bool
- func (p *Pool) Chain() *ChainBuilder
- func (p *Pool) DeadLetters() []JobOptions
- func (p *Pool) Diagnose() Diagnosis
- func (p *Pool) Drain(ctx context.Context) error
- func (p *Pool) Dump() string
- func (p *Pool) ExplainSaturation() string
- func (p *Pool) InspectJob(id string) (JobInfo, bool)
- func (p *Pool) IsPaused() bool
- func (p *Pool) IsQueuePaused(name string) bool
- func (p *Pool) IsRunning() bool
- func (p *Pool) Job(job Job) *JobBuilder
- func (p *Pool) JobFunc(fn func(context.Context) error) *JobBuilder
- func (p *Pool) JoinExisting(key string, job Job, opts ...JobOptions) error
- func (p *Pool) Lifecycle() *Lifecycle
- func (p *Pool) On(fn LifecycleHandler, types ...EventType) func()
- func (p *Pool) Once(key string, job Job, opts ...JobOptions) error
- func (p *Pool) OncePer(key string, ttl time.Duration, job Job, opts ...JobOptions) error
- func (p *Pool) Pause() error
- func (p *Pool) PauseQueue(name string)
- func (p *Pool) Prometheus() string
- func (p *Pool) PurgeDeadLetters() int
- func (p *Pool) Queue(name string) QueueHandle
- func (p *Pool) QueueDepth() int
- func (p *Pool) QueuePolicy(name string) (QueuePolicy, bool)
- func (p *Pool) Replace(key string, job Job, opts ...JobOptions) error
- func (p *Pool) ReplayDeadLetters() (int, error)
- func (p *Pool) Resize(workers int)
- func (p *Pool) Resume() error
- func (p *Pool) ResumeQueue(name string)
- func (p *Pool) ScheduleAfter(id string, after time.Duration, job Job, opts ...JobOptions) error
- func (p *Pool) ScheduleAt(id string, at time.Time, job Job, opts ...JobOptions) error
- func (p *Pool) ScheduleCron(id, expr string, job Job, opts ...JobOptions) (ScheduleHandle, error)
- func (p *Pool) ScheduleEvery(id string, every time.Duration, job Job, opts ...JobOptions) ScheduleHandle
- func (p *Pool) SetDefaultOptions(opt JobOptions)
- func (p *Pool) SetQueuePolicy(name string, policy QueuePolicy)
- func (p *Pool) SetRateLimit(key string, r RateLimit)
- func (p *Pool) Shutdown(ctx context.Context) error
- func (p *Pool) SpillDepth() int
- func (p *Pool) Start() error
- func (p *Pool) State() State
- func (p *Pool) Stats() Stats
- func (p *Pool) Stop(ctx context.Context) error
- func (p *Pool) Submit(job Job, opts ...JobOptions) error
- func (p *Pool) SubmitAny(payload any, handler AnyHandler, opts ...JobOptions) error
- func (p *Pool) SubmitBytes(data []byte, h func(context.Context, []byte) error, opts ...JobOptions) error
- func (p *Pool) SubmitFast(job Job) error
- func (p *Pool) SubmitFunc(fn func(context.Context) error, opts ...JobOptions) error
- func (p *Pool) SubmitJSON(data []byte, dst any, h func(context.Context, any) error, opts ...JobOptions) error
- func (p *Pool) SubmitMap(m map[string]any, h func(context.Context, map[string]any) error, ...) error
- func (p *Pool) SubmitResult(fn func(context.Context) (any, error), opts ...JobOptions) (Future[any], error)
- func (p *Pool) SubmitStruct(v any, h func(context.Context, any) error, opts ...JobOptions) error
- func (p *Pool) SubmitTask(arg any, fn func(context.Context, any) error, opts ...JobOptions) error
- func (p *Pool) Terminate() error
- func (p *Pool) UpdateQueueWeight(name string, priority Priority)
- func (p *Pool) UpdateRateLimit(key string, r RateLimit)
- func (p *Pool) Wait(ctx context.Context) error
- func (p *Pool) WaitIdle(ctx context.Context) error
- func (p *Pool) WhenAll(jobs ...Job) *WhenAllBuilder
- func (p *Pool) WorkerCount() int
- type Priority
- type Progress
- type QueueHandle
- func (q QueueHandle) Pause()
- func (q QueueHandle) Resume()
- func (q QueueHandle) Submit(job Job, opts ...JobOptions) error
- func (q QueueHandle) SubmitAny(payload any, h AnyHandler, opts ...JobOptions) error
- func (q QueueHandle) SubmitFunc(fn func(context.Context) error, opts ...JobOptions) error
- func (q QueueHandle) SubmitResult(fn func(context.Context) (any, error), opts ...JobOptions) (Future[any], error)
- type QueuePolicy
- type RateLimit
- type RateLimitMode
- type RetryableError
- type ScheduleHandle
- type State
- type Stats
- type Store
- type Task
- type TaskFunc
- type TestPool
- type TypedPool
- func (t *TypedPool[I, O]) Pause() error
- func (t *TypedPool[I, O]) Pool() *Pool
- func (t *TypedPool[I, O]) Resume() error
- func (t *TypedPool[I, O]) Start() error
- func (t *TypedPool[I, O]) Stats() Stats
- func (t *TypedPool[I, O]) Stop(ctx context.Context) error
- func (t *TypedPool[I, O]) Submit(ctx context.Context, in I, opts ...JobOptions) (Future[O], error)
- func (t *TypedPool[I, O]) Terminate() error
- type WhenAllBuilder
- type Worker
- type WorkerCloseFunc
- type WorkerInitFunc
Constants ¶
This section is empty.
Variables ¶
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 IsRetryable ¶
func MustShutdown ¶
func RunUntilSignal ¶
func ShutdownOnSignal ¶
Application integration.
func SubmitChannel ¶
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.
Types ¶
type AdminServer ¶
func (AdminServer) Handler ¶
func (a AdminServer) Handler() http.Handler
func (AdminServer) ListenAndServe ¶
func (a AdminServer) ListenAndServe(addr string) *http.Server
type AnyHandler ¶
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.
type BackpressurePolicy ¶
type BackpressurePolicy uint8
const ( BackpressureBlock BackpressurePolicy = iota BackpressureReject BackpressureDropOldest BackpressureDropNewest )
type BatchResult ¶
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) 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 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 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 (*FileStore) SaveDeadLetter ¶
type Future ¶
type Future[T any] interface { Get(context.Context) (T, error) Done() <-chan struct{} Cancel() bool }
func SubmitResult ¶
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 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 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) Timeout ¶
func (b *JobBuilder) Timeout(d time.Duration) *JobBuilder
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 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 ¶
type LifecycleHandler ¶
LifecycleHandler receives lifecycle events. Handlers must be fast. For slow operations use Lifecycle.SetAsync(true) or enqueue work into another system.
type Middleware ¶
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 PresetReliable ¶
func PresetReliable() Option
func WithAsyncLifecycle ¶
func WithAutoScale ¶
func WithBackpressure ¶
func WithBackpressure(b BackpressurePolicy) Option
func WithDefaultOptions ¶
func WithDefaultOptions(opt JobOptions) Option
func WithJobIDs ¶
func WithJobTracking ¶
func WithLifecycle ¶
func WithLifecycleHook ¶
func WithLifecycleHook(fn LifecycleHandler, types ...EventType) Option
func WithMiddleware ¶
func WithMiddleware(m ...Middleware) Option
func WithQueuePolicy ¶
func WithQueuePolicy(name string, policy QueuePolicy) Option
func WithQueueSize ¶
func WithRateLimit ¶
func WithRecoverPanics ¶
func WithSpillover ¶
func WithSubmitTimeout ¶
func WithWorkerClose ¶
func WithWorkerClose(fn WorkerCloseFunc) Option
func WithWorkerInit ¶
func WithWorkerInit(fn WorkerInitFunc) Option
func WithWorkerRange ¶
func WithWorkers ¶
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 MustNewPool ¶
func (*Pool) ActiveJobs ¶
func (*Pool) CancelJob ¶
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) Drain ¶
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) ExplainSaturation ¶
func (*Pool) InspectJob ¶
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) IsQueuePaused ¶
func (*Pool) Job ¶
func (p *Pool) Job(job Job) *JobBuilder
func (*Pool) JoinExisting ¶
func (p *Pool) JoinExisting(key string, job Job, opts ...JobOptions) error
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) PauseQueue ¶
func (*Pool) Prometheus ¶
func (*Pool) PurgeDeadLetters ¶
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 (*Pool) QueuePolicy ¶
func (p *Pool) QueuePolicy(name string) (QueuePolicy, bool)
func (*Pool) ReplayDeadLetters ¶
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) ResumeQueue ¶
func (*Pool) ScheduleAfter ¶
func (*Pool) ScheduleAt ¶
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 (*Pool) SpillDepth ¶
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 ¶
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 (*Pool) SubmitJSON ¶
func (*Pool) SubmitResult ¶
func (*Pool) SubmitStruct ¶
func (*Pool) SubmitTask ¶
SubmitTask submits stateful work without allocating a capturing closure.
func (*Pool) UpdateQueueWeight ¶
func (*Pool) UpdateRateLimit ¶
Runtime reconfiguration.
func (*Pool) WaitIdle ¶
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 ¶
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 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 ¶
Task is a small value-type Job. Passing Task[T] to Submit/SubmitFast avoids closure heap allocation while still carrying state through Arg.
type TaskFunc ¶
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
type WhenAllBuilder ¶
type WhenAllBuilder struct {
// contains filtered or unexported fields
}
func (*WhenAllBuilder) Options ¶
func (w *WhenAllBuilder) Options(opt JobOptions) *WhenAllBuilder
func (*WhenAllBuilder) Then ¶
func (w *WhenAllBuilder) Then(job Job) *WhenAllBuilder
func (*WhenAllBuilder) ThenFunc ¶
func (w *WhenAllBuilder) ThenFunc(fn func(context.Context) error) *WhenAllBuilder