{"modulePath":"github.com/golang-queue/queue","version":"v0.6.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package queue\n\n## Variables\n\n```go\nvar (\n\t// ErrNoTaskInQueue is returned by Worker.Request() when the queue is currently empty.\n\t// This is a temporary condition - new tasks may be added later.\n\t// The queue scheduler uses this error to determine when to retry or wait for notifications.\n\tErrNoTaskInQueue = errors.New(\"golang-queue: no task in queue\")\n\n\t// ErrQueueHasBeenClosed is returned by Worker.Request() during/after shutdown when no tasks remain.\n\t// This is a terminal state indicating the queue has been shut down and drained.\n\t// Once this error appears, no new tasks will be processed.\n\t// Triggered by: calling Shutdown() or Release() on the queue.\n\tErrQueueHasBeenClosed = errors.New(\"golang-queue: queue has been closed\")\n\n\t// ErrMaxCapacity is returned by Queue() or QueueTask() when the queue is at maximum capacity.\n\t// This only occurs when WithQueueSize() is used to set a capacity limit.\n\t// To handle: retry later, drop the task, or process it synchronously.\n\t// Triggered by: attempting to enqueue when count \u003e= capacity.\n\tErrMaxCapacity = errors.New(\"golang-queue: maximum size limit reached\")\n)\n```\n\n```go\nvar ErrMissingWorker = errors.New(\"missing worker module\")\n```\nErrMissingWorker is returned when a queue is created without a worker implementation.\n\n```go\nvar ErrQueueShutdown = errors.New(\"queue has been closed and released\")\n```\nErrQueueShutdown is returned when an operation is attempted on a queue that has already been closed and released.\n\n## Types\n\n```go\ntype Logger interface {\n\t// Infof logs formatted informational messages.\n\tInfof(format string, args ...any)\n\n\t// Errorf logs formatted error messages.\n\tErrorf(format string, args ...any)\n\n\t// Fatalf logs formatted fatal errors with stack trace information.\n\t// Used for panics and critical failures.\n\tFatalf(format string, args ...any)\n\n\t// Info logs informational messages.\n\tInfo(args ...any)\n\n\t// Error logs error messages.\n\tError(args ...any)\n\n\t// Fatal logs fatal errors with stack trace information.\n\t// Used for panics and critical failures.\n\tFatal(args ...any)\n}\n```\nLogger defines the interface for logging queue events, errors, and fatal conditions. The queue uses this interface to report:\n\n  - Info: Normal operations (shutdown, retry attempts)\n  - Error: Recoverable errors (task failures, runtime errors)\n  - Fatal: Panics and critical failures (includes stack traces)\n\nImplement this interface to integrate with custom logging systems (logrus, zap, etc.).\n\n```go\nfunc NewEmptyLogger() Logger\n```\nNewEmptyLogger creates a no-op logger that discards all log messages. This is useful for:\n\n  - Performance-sensitive production environments where logging overhead matters\n  - Testing scenarios where log output would clutter test results\n  - Silent background workers that don't need observability\n\nExample:\n\n\tq := queue.NewPool(5, queue.WithLogger(queue.NewEmptyLogger()))\n\n```go\nfunc NewLogger() Logger\n```\nNewLogger creates a standard logger that writes to stderr with timestamps. This is the default logger used by queues unless overridden with WithLogger.\n\nLog format:\n\n  - INFO messages: Simple timestamped output\n  - ERROR messages: Simple timestamped output\n  - FATAL messages: Includes stack trace with file:line information\n\nUse cases:\n\n  - Development and debugging\n  - Simple production deployments without structured logging\n  - When detailed error context is needed\n\n```go\ntype Metric interface {\n\t// IncBusyWorker increments the count of workers currently processing tasks.\n\t// Called atomically when a worker starts processing a job.\n\tIncBusyWorker()\n\n\t// DecBusyWorker decrements the count of workers currently processing tasks.\n\t// Called atomically when a worker finishes processing a job (success or failure).\n\tDecBusyWorker()\n\n\t// BusyWorkers returns the current number of workers actively processing tasks.\n\t// This value can range from 0 to the configured workerCount.\n\tBusyWorkers() int64\n\n\t// SuccessTasks returns the total number of tasks that completed successfully.\n\t// A task is considered successful if it returns no error and doesn't panic.\n\tSuccessTasks() uint64\n\n\t// FailureTasks returns the total number of tasks that failed.\n\t// A task is considered failed if it returns an error, panics, or times out.\n\tFailureTasks() uint64\n\n\t// SubmittedTasks returns the total number of tasks submitted to the queue.\n\t// This includes tasks still pending, in progress, and completed.\n\tSubmittedTasks() uint64\n\n\t// CompletedTasks returns the total number of tasks that have finished processing.\n\t// This equals SuccessTasks() + FailureTasks().\n\tCompletedTasks() uint64\n\n\t// IncSuccessTask increments the successful task counter.\n\t// Called atomically after a task completes without error.\n\tIncSuccessTask()\n\n\t// IncFailureTask increments the failed task counter.\n\t// Called atomically after a task fails, panics, or times out.\n\tIncFailureTask()\n\n\t// IncSubmittedTask increments the submitted task counter.\n\t// Called atomically when a new task is queued.\n\tIncSubmittedTask()\n}\n```\nMetric defines the interface for tracking queue performance and worker statistics. All methods must be safe for concurrent access from multiple goroutines. Implement this interface to integrate with custom monitoring systems (Prometheus, StatsD, etc.).\n\n```go\nfunc NewMetric() Metric\n```\nNewMetric creates a new metric collector with all counters initialized to zero. The returned metric is safe for concurrent use.\n\n```go\ntype Option interface {\n\t// contains filtered or unexported methods\n}\n```\nOption is a functional option for configuring a Queue. It follows the functional options pattern for flexible and extensible configuration.\n\n```go\nfunc WithAfterFn(afterFn func()) Option\n```\nWithAfterFn sets a callback function that will be executed after each job completes. This callback runs regardless of whether the job succeeded or failed. It executes after metrics are updated without occupying a worker slot. Callbacks may overlap; Release waits for them to finish. Useful for cleanup, logging, or triggering post-processing workflows.\n\nExample:\n\n\tq := NewPool(5, WithAfterFn(func() {\n\t    log.Println(\"Job completed\")\n\t}))\n\n```go\nfunc WithFn(fn func(context.Context, core.TaskMessage) error) Option\n```\nWithFn sets a custom handler function that will be called to process tasks. This function is used by the worker's Run method when processing job messages. The context allows cancellation and timeout control during task execution. If not set, defaults to a no-op function that returns nil.\n\nExample:\n\n\thandler := func(ctx context.Context, msg core.TaskMessage) error {\n\t    // Process the message\n\t    return processTask(msg)\n\t}\n\tq := NewPool(5, WithFn(handler))\n\n```go\nfunc WithLogger(l Logger) Option\n```\nWithLogger sets a custom logger for queue events and errors. By default, the queue uses a standard logger that writes to stderr. Use NewEmptyLogger() to disable logging entirely.\n\nExample:\n\n\tq := NewPool(5, WithLogger(myCustomLogger))\n\t// or disable logging:\n\tq := NewPool(5, WithLogger(NewEmptyLogger()))\n\n```go\nfunc WithMetric(m Metric) Option\n```\nWithMetric sets a custom metrics collector for tracking queue statistics. The default metric tracks busy workers, success/failure counts, and submitted tasks. Implement the Metric interface to integrate with custom monitoring systems.\n\nExample:\n\n\tq := NewPool(5, WithMetric(myPrometheusMetric))\n\n```go\nfunc WithQueueSize(num int) Option\n```\nWithQueueSize sets the maximum capacity of the queue. When set to 0 (default), the queue has unlimited capacity and will grow dynamically. When set to a positive value, Queue() will return ErrMaxCapacity when the limit is reached. Use this to prevent memory exhaustion under high load.\n\nExample:\n\n\tq := NewPool(5, WithQueueSize(1000)) // Queue will hold at most 1000 pending tasks\n\n```go\nfunc WithRetryInterval(d time.Duration) Option\n```\nWithRetryInterval sets the interval at which the queue polls for new tasks when the queue is empty. This determines how often Request() is retried after receiving ErrNoTaskInQueue. Lower values provide faster response to new tasks but increase CPU usage. Defaults to 1 second.\n\nExample:\n\n\tq := NewPool(5, WithRetryInterval(100*time.Millisecond)) // Poll every 100ms\n\n```go\nfunc WithWorker(w core.Worker) Option\n```\nWithWorker sets a custom worker implementation for the queue backend. By default, NewPool uses an in-memory Ring buffer worker. Use this to integrate external queue systems like NSQ, NATS, Redis, or RabbitMQ. This option is required when using NewQueue() instead of NewPool().\n\nExample:\n\n\tq, _ := NewQueue(WithWorker(myNSQWorker), WithWorkerCount(10))\n\n```go\nfunc WithWorkerCount(num int64) Option\n```\nWithWorkerCount sets the number of concurrent worker goroutines that will process jobs. If num is less than or equal to 0, it defaults to runtime.NumCPU(). More workers allow higher concurrency but consume more system resources.\n\nExample:\n\n\tq := NewPool(10, WithWorkerCount(4)) // Creates a pool with 4 workers\n\n```go\ntype OptionFunc func(*Options)\n```\nOptionFunc is a function adapter that implements the Option interface. It allows regular functions to be used as Options.\n\n```go\ntype Options struct {\n\t// contains filtered or unexported fields\n}\n```\nOptions holds the configuration parameters for a Queue. Use the With\\* functions to configure these options when creating a queue.\n\n```go\nfunc NewOptions(opts ...Option) *Options\n```\nNewOptions creates an Options struct with default values and applies any provided options. Default values:\n\n  - workerCount: runtime.NumCPU()\n  - queueSize: 0 (unlimited)\n  - logger: stderr logger with timestamps\n  - worker: nil (must be provided via WithWorker or use NewPool which sets Ring)\n  - fn: no-op function returning nil\n  - metric: built-in metric tracker\n  - retryInterval: 1 second\n\n```go\ntype Queue struct {\n\tsync.Mutex // Mutex to protect concurrent access to queue state\n\t// contains filtered or unexported fields\n}\n```\nQueue represents a message queue with worker management, job scheduling, retry logic, and graceful shutdown capabilities.\n\n```go\nfunc NewPool(size int64, opts ...Option) *Queue\n```\nNewPool creates a ready-to-use in-memory queue with the Ring buffer worker. This is the recommended way to create a queue for most use cases.\n\nKey differences from NewQueue:\n\n  - Automatically creates and attaches a Ring buffer worker (no need for WithWorker)\n  - Calls Start() automatically so the queue begins processing immediately\n  - Panics on error instead of returning an error (simplifies initialization)\n\nParameters:\n\n  - size: Number of worker goroutines (if \\\u003c= 0, defaults to runtime.NumCPU())\n  - opts: Additional options to customize the queue (WithLogger, WithQueueSize, etc.)\n\nExample:\n\n\t// Create a pool with 5 workers and custom capacity\n\tq := queue.NewPool(5, queue.WithQueueSize(100))\n\tdefer q.Release()\n\n\t// Queue tasks\n\tq.QueueTask(func(ctx context.Context) error {\n\t    // Process task\n\t    return nil\n\t})\n\nUse NewQueue instead if you need:\n\n  - Custom worker implementations (NSQ, NATS, Redis, etc.)\n  - Manual control over when to start the queue\n  - Error handling during queue creation\n\n```go\nfunc NewQueue(opts ...Option) (*Queue, error)\n```\nNewQueue creates and returns a new Queue instance with the provided options. Returns an error if no worker is specified.\n\n```go\nfunc (q *Queue) BusyWorkers() int64\n```\nBusyWorkers returns the number of workers currently processing jobs.\n\n```go\nfunc (q *Queue) CompletedTasks() uint64\n```\nCompletedTasks returns the total number of completed tasks (success + failure).\n\n```go\nfunc (q *Queue) FailureTasks() uint64\n```\nFailureTasks returns the number of failed tasks.\n\n```go\nfunc (q *Queue) Queue(message core.QueuedMessage, opts ...job.AllowOption) error\n```\nQueue enqueues a single job (core.QueuedMessage) into the queue. Accepts job options for customization.\n\n```go\nfunc (q *Queue) QueueTask(task job.TaskFunc, opts ...job.AllowOption) error\n```\nQueueTask enqueues a single task function into the queue. Accepts job options for customization.\n\n```go\nfunc (q *Queue) Release()\n```\nRelease performs a graceful shutdown and waits for all goroutines to finish.\n\n```go\nfunc (q *Queue) Shutdown()\n```\nShutdown initiates a graceful shutdown of the queue. It signals all goroutines to stop, shuts down the worker, and closes the quit channel. Shutdown is idempotent and safe to call multiple times.\n\n```go\nfunc (q *Queue) Start()\n```\nStart launches the dispatcher and workers once and begins processing jobs. If workerCount is zero, Start is a no-op.\n\n```go\nfunc (q *Queue) SubmittedTasks() uint64\n```\nSubmittedTasks returns the number of tasks submitted to the queue.\n\n```go\nfunc (q *Queue) SuccessTasks() uint64\n```\nSuccessTasks returns the number of successfully completed tasks.\n\n```go\nfunc (q *Queue) UpdateWorkerCount(num int64)\n```\nUpdateWorkerCount dynamically updates the number of worker goroutines. Triggers scheduling to adjust to the new worker count.\n\n```go\nfunc (q *Queue) Wait()\n```\nWait blocks until all goroutines in the routine group have finished.\n\n```go\ntype Ring struct {\n\tsync.Mutex\n\t// contains filtered or unexported fields\n}\n```\nRing is an in-memory worker implementation using a dynamic circular buffer. It implements the core.Worker interface and provides automatic resizing:\n\n  - Doubles capacity when full\n  - Halves capacity when at most 25% utilized\n\nThe ring buffer uses two pointers (head and tail) to track the queue boundaries:\n\n  - head: points to the next task to dequeue\n  - tail: points to the next empty slot for enqueuing\n  - When head == tail, the queue is empty\n  - Both pointers wrap around using modulo arithmetic\n\n```go\nfunc NewRing(opts ...Option) *Ring\n```\nNewRing creates a new Ring instance with the provided options. It initializes the task queue with a default size of 2, sets the capacity based on the provided options, and configures the logger and run function. The function returns a pointer to the newly created Ring instance.\n\nParameters:\n\n\topts - A variadic list of Option functions to configure the Ring instance.\n\nReturns:\n\n\t*Ring - A pointer to the newly created Ring instance.\n\n```go\nfunc (s *Ring) Queue(task core.TaskMessage) error\n```\nQueue adds a task to the ring buffer. The buffer grows dynamically (doubles in size) when full, unless capacity is set. Returns ErrQueueShutdown if the queue is closing, or ErrMaxCapacity if at the size limit.\n\nThread-safety: This method is safe for concurrent calls.\n\n```go\nfunc (s *Ring) Request() (core.TaskMessage, error)\n```\nRequest dequeues and returns the next task from the ring buffer. The buffer shrinks automatically (halves in size) when at most 25% full. Returns:\n\n  - (task, nil) if a task is successfully dequeued\n  - (nil, ErrNoTaskInQueue) if the queue is currently empty\n  - (nil, ErrQueueHasBeenClosed) if shutdown is complete and the queue is empty\n\nDuring shutdown, this method signals the exit channel when the last task is dequeued, allowing Shutdown() to complete.\n\nThread-safety: This method is safe for concurrent calls.\n\n```go\nfunc (s *Ring) Run(ctx context.Context, task core.TaskMessage) error\n```\nRun executes a new task using the provided context and task message. It calls the runFunc function, which is responsible for processing the task. The context allows for cancellation and timeout control of the task execution.\n\n```go\nfunc (s *Ring) Shutdown() error\n```\nShutdown gracefully shuts down the worker. It sets the stopFlag to indicate that the queue is shutting down and prevents new tasks from being added. If the queue is already shut down, it returns ErrQueueShutdown. It waits for all tasks to be processed before completing the shutdown.\n\n","path":"github.com/golang-queue/queue","name":"queue","synopsis":"","isRedistributable":true}
