{"modulePath":"github.com/mutablelogic/go-pg","version":"v1.1.15","isLatest":false,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package queue\n\nPackage queue provides a PostgreSQL-backed task queue with support for delayed tasks, retries with exponential backoff, and periodic tickers.\n\n### Manager {#hdr-Manager}\n\nCreate a manager with namespace isolation:\n\n\tmgr, err := queue.New(ctx, pool, queue.WithNamespace(\"myapp\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n### Queues {#hdr-Queues}\n\nRegister queues that define retry behavior:\n\n\tttl := 24 * time.Hour\n\tretries := uint64(3)\n\tretryDelay := time.Minute\n\n\tqueue, err := mgr.RegisterQueue(ctx, schema.QueueMeta{\n\t\tQueue:      \"emails\",\n\t\tTTL:        \u0026ttl,\n\t\tRetries:    \u0026retries,\n\t\tRetryDelay: \u0026retryDelay,\n\t})\n\n### Tasks {#hdr-Tasks}\n\nCreate and process tasks:\n\n\t// Create a task\n\ttask, err := mgr.CreateTask(ctx, \"emails\", schema.TaskMeta{\n\t\tPayload: map[string]any{\"to\": \"user@example.com\"},\n\t})\n\n\t// Retain next task from a specific queue\n\ttask, err := mgr.NextTask(ctx, \"worker-1\", \"emails\")\n\n\t// Retain next task from any queue\n\ttask, err := mgr.NextTask(ctx, \"worker-1\")\n\n\t// Retain next task from multiple queues\n\ttask, err := mgr.NextTask(ctx, \"worker-1\", \"emails\", \"notifications\")\n\n\t// Release task (success)\n\tmgr.ReleaseTask(ctx, task.Id, true, nil, \u0026status)\n\n\t// Release task (failure - will retry with backoff)\n\tmgr.ReleaseTask(ctx, task.Id, false, errPayload, \u0026status)\n\n### WorkerPool {#hdr-WorkerPool}\n\nUse WorkerPool for concurrent task processing:\n\n\tpool, err := queue.NewWorkerPool(mgr,\n\t\tqueue.WithWorkers(4),\n\t\tqueue.WithWorkerName(\"worker-1\"),\n\t)\n\n\t// Register queue handlers\n\tpool.RegisterQueue(ctx, schema.QueueMeta{Queue: \"emails\"}, func(ctx context.Context, task *schema.Task) error {\n\t\t// Process task\n\t\treturn nil\n\t})\n\n\t// Run blocks until context is cancelled\n\terr = pool.Run(ctx)\n\n### Tickers {#hdr-Tickers}\n\nRegister periodic tickers:\n\n\tinterval := time.Hour\n\tticker, err := mgr.RegisterTicker(ctx, schema.TickerMeta{\n\t\tTicker:   \"hourly-report\",\n\t\tInterval: \u0026interval,\n\t})\n\n### Subpackages {#hdr-Subpackages}\n\n  - schema: Data types, request/response structures, and SQL generation\n  - httphandler: REST API handlers for all queue operations\n  - httpclient: Typed Go client for the REST API\n\n## Variables\n\n```go\nvar (\n\tErrInvalidNamespace  = errors.New(\"namespace must not be empty\")\n\tErrReservedNamespace = errors.New(\"namespace is reserved for system use\")\n\tErrInvalidWorkers    = errors.New(\"workers must be \u003e= 1\")\n\tErrInvalidPeriod     = errors.New(\"period must be \u003e= 1ms\")\n)\n```\n\n## Functions\n\n```go\nfunc WithLogger(ctx context.Context, log *slog.Logger) context.Context\n```\nWithLogger stores a \\*slog.Logger in the context for use by Run.\n\n## Types\n\n```go\ntype Manager struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc New(ctx context.Context, conn pg.PoolConn, opts ...Opt) (*Manager, error)\n```\nNew creates a new queue manager. Use WithNamespace to set the namespace for all queue operations.\n\n```go\nfunc (manager *Manager) CleanQueue(ctx context.Context, name string) ([]schema.Task, error)\n```\nCleanQueue removes stale tasks from a queue, and returns the tasks removed\n\n```go\nfunc (manager *Manager) Conn() pg.PoolConn\n```\n\n```go\nfunc (manager *Manager) CreateTask(ctx context.Context, queue string, meta schema.TaskMeta) (*schema.Task, error)\n```\nCreateTask creates a new task, and returns it.\n\n```go\nfunc (manager *Manager) DeleteQueue(ctx context.Context, name string) (*schema.Queue, error)\n```\nDeleteQueue deletes an existing queue, and returns it\n\n```go\nfunc (manager *Manager) DeleteTicker(ctx context.Context, name string) (*schema.Ticker, error)\n```\nDeleteTicker deletes an existing ticker, and returns the deleted ticker.\n\n```go\nfunc (manager *Manager) GetQueue(ctx context.Context, name string) (*schema.Queue, error)\n```\nGetQueue returns a queue by name\n\n```go\nfunc (manager *Manager) GetTicker(ctx context.Context, name string) (*schema.Ticker, error)\n```\nGetTicker returns a ticker by name\n\n```go\nfunc (manager *Manager) ListNamespaces(ctx context.Context, req schema.NamespaceListRequest) (*schema.NamespaceList, error)\n```\nListNamespaces returns all distinct namespaces from the queue table\n\n```go\nfunc (manager *Manager) ListQueueStatuses(ctx context.Context) ([]schema.QueueStatus, error)\n```\nListQueueStatuses returns the status breakdown for all queues in the namespace\n\n```go\nfunc (manager *Manager) ListQueues(ctx context.Context, req schema.QueueListRequest) (*schema.QueueList, error)\n```\nListQueues returns all queues in a namespace as a list\n\n```go\nfunc (manager *Manager) ListTasks(ctx context.Context, req schema.TaskListRequest) (*schema.TaskList, error)\n```\nListTasks returns all tasks in a namespace as a list, with optional filtering\n\n```go\nfunc (manager *Manager) ListTickers(ctx context.Context, req schema.TickerListRequest) (*schema.TickerList, error)\n```\nListTickers returns all tickers in a namespace as a list\n\n```go\nfunc (manager *Manager) Namespace() string\n```\n\n```go\nfunc (manager *Manager) NextTask(ctx context.Context, worker string, queues ...string) (*schema.Task, error)\n```\nNextTask retains a task from any of the specified queues, and returns it. If queues is empty, tasks from any queue are considered. Returns nil if there is no task to retain.\n\n```go\nfunc (manager *Manager) NextTicker(ctx context.Context) (*schema.Ticker, error)\n```\nNextTicker returns the next matured ticker, or nil\n\n```go\nfunc (manager *Manager) NextTickerNs(ctx context.Context, namespace string) (*schema.Ticker, error)\n```\nNextTickerNs returns the next matured ticker in a namespace, or nil\n\n```go\nfunc (manager *Manager) RegisterQueue(ctx context.Context, meta schema.QueueMeta) (*schema.Queue, error)\n```\nRegisterQueue creates a new queue, or updates an existing queue, and returns it.\n\n```go\nfunc (manager *Manager) RegisterQueueWorker(ctx context.Context, meta schema.QueueMeta, worker Worker) (*schema.Queue, error)\n```\nRegisterQueueWorker registers a queue with its worker and creates/updates it in the database.\n\n```go\nfunc (manager *Manager) RegisterTicker(ctx context.Context, meta schema.TickerMeta) (*schema.Ticker, error)\n```\nRegisterTicker creates a new ticker, or updates an existing ticker, and returns it.\n\n```go\nfunc (manager *Manager) RegisterTickerNs(ctx context.Context, namespace string, meta schema.TickerMeta) (*schema.Ticker, error)\n```\nRegisterTicker creates a new ticker, or updates an existing ticker, and returns it.\n\n```go\nfunc (manager *Manager) RegisterTickerWorker(ctx context.Context, meta schema.TickerMeta, worker Worker) (*schema.Ticker, error)\n```\nRegisterTickerWorker registers a ticker with its worker and creates/updates it in the database.\n\n```go\nfunc (manager *Manager) ReleaseTask(ctx context.Context, task uint64, success bool, result any, status *string) (*schema.Task, error)\n```\nReleaseTask releases a task from a queue, and returns it. Can optionally set the status\n\n```go\nfunc (manager *Manager) Run(ctx context.Context) error\n```\nRun starts the cleanup ticker and all registered task and ticker workers, blocking until context is cancelled or an error occurs.\n\n```go\nfunc (manager *Manager) RunTaskLoop(ctx context.Context, handler TaskHandler, queues ...string) error\n```\nRunTaskLoop runs a task loop with N concurrent workers. This is a low-level API - most users should use RegisterQueueWorker + Run() instead.\n\nEach worker calls the handler function when a task is received. The handler is responsible for:\n\n  - Processing the task\n  - Calling ReleaseTask to mark the task as completed or failed\n  - Returning an error if the task processing failed\n\nNote: The handler runs in a background goroutine, so any error returned is already tracked in OpenTelemetry spans but won't propagate to the caller.\n\nBlocks until context is cancelled. If queues is empty, tasks from any queue are considered. The worker name (from WithWorkerName) will have @N appended for each concurrent worker (e.g., \"hostname@1\"). The number of workers is set via WithWorkers option.\n\n```go\nfunc (manager *Manager) RunTickerLoop(ctx context.Context, period time.Duration, handler TickerHandler) error\n```\nRunTickerLoop runs a loop to process matured tickers with a single worker. The handler is called for each matured ticker. Blocks until context is cancelled or an error occurs.\n\n```go\nfunc (manager *Manager) RunTickerLoopChan(ctx context.Context, ch chan\u003c- *schema.Ticker, period time.Duration) error\n```\nRunTickerLoopChan runs a loop to process matured tickers, sending them to a channel. Use this for streaming scenarios where you need direct channel access. The caller owns the channel and must close it when done. Blocks until context is cancelled or an error occurs.\n\n```go\nfunc (manager *Manager) RunTickerLoopNs(ctx context.Context, namespace string, period time.Duration, handler TickerHandler) error\n```\nRunTickerLoopNs runs a loop to process matured tickers in a specific namespace with a single worker. The handler is called for each matured ticker. Blocks until context is cancelled or an error occurs.\n\n```go\nfunc (manager *Manager) RunTickerLoopNsChan(ctx context.Context, namespace string, ch chan\u003c- *schema.Ticker, period time.Duration) error\n```\nRunTickerLoopNsChan runs a loop to process matured tickers in a namespace, sending them to a channel. Use this for streaming scenarios where you need direct channel access. The caller owns the channel and must close it when done. Blocks until context is cancelled or an error occurs.\n\n```go\nfunc (manager *Manager) UpdateQueue(ctx context.Context, name string, meta schema.QueueMeta) (*schema.Queue, error)\n```\nUpdateQueue updates an existing queue, and returns it.\n\n```go\nfunc (manager *Manager) UpdateTicker(ctx context.Context, name string, meta schema.TickerMeta) (*schema.Ticker, error)\n```\nUpdateTicker updates an existing ticker, and returns it.\n\n```go\ntype Opt func(*opts) error\n```\nOpt is a functional option for worker pool, queue, and ticker configuration.\n\n```go\nfunc WithNamespace(name string) Opt\n```\nWithNamespace sets the namespace used to scope all queue operations. The namespace cannot be empty or use the reserved system namespace.\n\n```go\nfunc WithPeriod(d time.Duration) Opt\n```\nWithPeriod sets the polling period for a ticker. Returns ErrInvalidPeriod if d \\\u003c 1ms.\n\n```go\nfunc WithTracer(tracer trace.Tracer) Opt\n```\nWithTracer sets the tracer used for tracing operations.\n\n```go\nfunc WithWorkerName(name string) Opt\n```\nWithWorkerName sets the worker name used to identify this worker instance. Defaults to the hostname if not specified.\n\n```go\nfunc WithWorkers(n int) Opt\n```\nWithWorkers sets the number of concurrent workers for the worker pool. The worker pool uses a shared pool of workers to process tasks from any registered queue. Returns ErrInvalidWorkers if n \\\u003c 1.\n\n```go\ntype TaskHandler func(context.Context, *schema.Task) error\n```\nTaskHandler processes a task. Return nil on success, or an error to fail the task.\n\n```go\ntype TickerHandler func(context.Context, *schema.Ticker) error\n```\nTickerHandler processes a ticker. Return nil on success, or an error on failure.\n\n```go\ntype Worker interface {\n\tRun(ctx context.Context, payload json.RawMessage) error\n}\n```\nWorker processes a task or ticker payload. Return nil on success, or an error to indicate failure.\n\n","path":"github.com/mutablelogic/go-pg/pkg/queue","name":"queue","synopsis":"Package queue provides a PostgreSQL-backed task queue with support for delayed tasks, retries with exponential backoff, and periodic tickers.","isRedistributable":true}
