Documentation
ΒΆ
Index ΒΆ
- func CalculateDynamicQueueSize() int
- func DecodeTaskData(encoded string, target interface{}) error
- func DeleteTask(taskId string) error
- func EncodeTaskData(data interface{}) (string, error)
- func EnsureTaskTypesRegistered()
- func GetRegisteredTaskFactory(retryableTask RetryableTask) (func(id string, data string) (Task, error), bool)
- func LogQueueUsage(ctx context.Context, queue *AnyQueue, wg *sync.WaitGroup)
- func ProcessInMemoryQueue(ctx context.Context, queue *AnyQueue, wg *sync.WaitGroup)
- func ProcessRetryQueue(ctx context.Context, queue *AnyQueue, wg *sync.WaitGroup, ...)
- func RegisterInitFunction(fn InitFunction)
- func RegisterMaxRetryHandler(taskType string, handler OnMaxRetryHandler)
- func RegisterTaskHandler(taskType string, handler TaskHandler)
- func RegisterTaskType[P any](taskType string, creator func(id string, payload P) Task)
- func SerializeTaskPayload[P any](payload P) (string, error)
- type AnyQueue
- func (q *AnyQueue) Enqueue(task Task) error
- func (q *AnyQueue) EnqueueSnerdTask(task *SnerdTask) error
- func (q *AnyQueue) Name() string
- func (q *AnyQueue) ProcessDueTasks()
- func (q *AnyQueue) RemainingCapacity() int
- func (q *AnyQueue) Size() int
- func (q *AnyQueue) StartDashboard(port int)
- func (q *AnyQueue) StopProcessor()
- func (q *AnyQueue) SubscribeProgress() <-chan string
- func (q *AnyQueue) TotalEnqueued() int
- func (q *AnyQueue) TotalProcessed() int
- func (q *AnyQueue) YieldProgress(taskID string, data string)
- type FileStore
- func (fs *FileStore) Compact() error
- func (fs *FileStore) CreateTask(task *RetryableTask) error
- func (fs *FileStore) DeleteTask(taskID string) error
- func (fs *FileStore) GetLatestTask(taskID string) (*RetryableTask, error)
- func (fs *FileStore) ReadDueTasks() ([]*RetryableTask, error)
- func (fs *FileStore) ReadTasks() ([]*RetryableTask, error)
- func (fs *FileStore) RebuildMetaData() error
- func (fs *FileStore) UpdateTaskRetryConfig(taskID string, taskErr error) error
- type InitFunction
- type JobErrorReturn
- type OnMaxRetryHandler
- type PriorityQueue
- type RateLimitEntry
- type RateLimiter
- type RetryableTask
- func (t *RetryableTask) Execute(ctx context.Context) error
- func (t *RetryableTask) GenerateRandomString(length int) (string, error)
- func (t *RetryableTask) GetMaxRetries() int
- func (t *RetryableTask) GetRetryAfterHours() float64
- func (t *RetryableTask) GetRetryAfterTime() time.Time
- func (t *RetryableTask) GetRetryCount() int
- func (t *RetryableTask) GetTaskID() string
- func (t *RetryableTask) MarshalJSON() ([]byte, error)
- func (t *RetryableTask) Save() error
- func (t *RetryableTask) UnmarshalJSON(data []byte) error
- func (t *RetryableTask) UpdateTaskRetryConfig(taskId string) error
- func (t *RetryableTask) UpdateTaskRetryConfigWithError(taskId string, errorObj error) error
- type SnerdTask
- func CreateTask(taskID string, taskType string, parameters interface{}, maxRetries int, ...) (*SnerdTask, error)
- func FromRetryableTask(rt *RetryableTask) *SnerdTask
- func NewSnerdTask(taskID string, taskType string, parameters interface{}, maxRetries int, ...) (*SnerdTask, error)
- func NewSnerdTaskAdvanced(taskID string, taskType string, parameters interface{}, maxRetries int, ...) (*SnerdTask, error)
- func (t *SnerdTask) Execute(ctx context.Context) error
- func (t *SnerdTask) GetMaxRetries() int
- func (t *SnerdTask) GetRetryAfterHours() float64
- func (t *SnerdTask) GetRetryAfterTime() time.Time
- func (t *SnerdTask) GetRetryCount() int
- func (t *SnerdTask) GetTaskID() string
- func (t *SnerdTask) OnMaxRetryReached(ctx context.Context, contextProvider func() interface{}) error
- func (t *SnerdTask) String() string
- func (t *SnerdTask) ToRetryableTask() *RetryableTask
- func (t *SnerdTask) UpdateRetryConfig(errorObj error)
- type Task
- type TaskFactory
- type TaskHandler
- type TaskWithData
- type TaskWithMaxRetryCallback
Constants ΒΆ
This section is empty.
Variables ΒΆ
This section is empty.
Functions ΒΆ
func CalculateDynamicQueueSize ΒΆ
func CalculateDynamicQueueSize() int
CalculateDynamicQueueSize returns an optimal queue size based on system resources. It uses available CPU and memory to auto-scale queue capacity.
func DecodeTaskData ΒΆ
Helper method to decode task data from JSON
func DeleteTask ΒΆ
DeleteTask removes a task from the database by its TaskID
func EncodeTaskData ΒΆ
Helper method to encode task data into JSON and save it
func EnsureTaskTypesRegistered ΒΆ
func EnsureTaskTypesRegistered()
EnsureTaskTypesRegistered ensures that all known task types are registered This is called before processing tasks to prevent the "no factory registered" error
func GetRegisteredTaskFactory ΒΆ
func GetRegisteredTaskFactory(retryableTask RetryableTask) (func(id string, data string) (Task, error), bool)
GetRegisteredTaskFactory returns a task factory for a specific task type
func LogQueueUsage ΒΆ
LogQueueUsage monitors a queue and logs its stats periodically. Logging stops automatically when the queue is empty or when the context is canceled.
func ProcessInMemoryQueue ΒΆ
ProcessInMemoryQueue processes tasks in an in-memory queue with proper rate limiting This is specifically for NON-retryable, in-memory tasks only
func ProcessRetryQueue ΒΆ
func ProcessRetryQueue(ctx context.Context, queue *AnyQueue, wg *sync.WaitGroup, interval time.Duration)
ProcessRetryQueue starts a background goroutine that periodically processes retryable tasks. It polls for due tasks at the specified interval and processes them using the provided queue. ProcessRetryQueue starts a goroutine that processes a queue at regular intervals.
func RegisterInitFunction ΒΆ
func RegisterInitFunction(fn InitFunction)
RegisterInitFunction registers a function to be called when ensuring task types are registered This allows packages to register their task types without circular dependencies
func RegisterMaxRetryHandler ΒΆ
func RegisterMaxRetryHandler(taskType string, handler OnMaxRetryHandler)
RegisterMaxRetryHandler registers a handler for when a task reaches max retries
func RegisterTaskHandler ΒΆ
func RegisterTaskHandler(taskType string, handler TaskHandler)
RegisterTaskHandler registers a handler for a specific task type
func RegisterTaskType ΒΆ
RegisterTaskType registers a task type with a factory function This allows tasks to be recreated from their saved data
func SerializeTaskPayload ΒΆ
SerializeTaskPayload serializes a task payload for storage This allows client code to create task data without knowing serialization details
Types ΒΆ
type AnyQueue ΒΆ
type AnyQueue struct {
// contains filtered or unexported fields
}
AnyQueue is a thread-safe queue that manages SnerdTask execution, retry logic, and statistics
func NewAnyQueue ΒΆ
func NewAnyQueue(args ...interface{}) *AnyQueue
NewAnyQueue creates a new queue with the given parameters
func NewAnyQueueWithStorage ΒΆ added in v0.2.5
func NewAnyQueueWithStorage(name string, maxSize int, processingInterval time.Duration, taskStorePath string) *AnyQueue
NewAnyQueueWithStorage creates a new queue that persists tasks to a custom file location instead of the default ./.snerdata/tasks/tasks.log. This is useful for isolating queues per concern, pointing at a shared network drive (e.g. EFS/NFS) for cross-process queue sharing, or test isolation.
func (*AnyQueue) EnqueueSnerdTask ΒΆ
EnqueueSnerdTask adds a parameter-based SnerdTask to the queue for execution This is the preferred method for adding new tasks as it uses the parameter-based approach that doesn't require client-side task registration
func (*AnyQueue) ProcessDueTasks ΒΆ
func (q *AnyQueue) ProcessDueTasks()
ProcessDueTasks processes all tasks that are due for execution (retry time has passed)..
func (*AnyQueue) RemainingCapacity ΒΆ
RemainingCapacity returns the number of additional tasks that can be enqueued before reaching maxSize..
func (*AnyQueue) StartDashboard ΒΆ
StartDashboard starts the built-in dashboard UI on the given port.
The dashboard is a single-page React app (served from ./static/index.html relative to the process working directory) that shows live queue stats, a Recent Jobs table, and a real-time Progress Stream fed by YieldProgress. Updates are delivered via HTTP polling of the JSON API (/api/stats, /api/tasks, /api/progress).
The dashboard only serves the UI β jobs keep running whether or not it is open.
func (*AnyQueue) StopProcessor ΒΆ
func (q *AnyQueue) StopProcessor()
StopProcessor stops the background task processor
func (*AnyQueue) SubscribeProgress ΒΆ
SubscribeProgress returns a channel that receives real-time task progress JSON chunks.
func (*AnyQueue) TotalEnqueued ΒΆ
TotalEnqueued returns the total number of tasks that have been enqueued.
func (*AnyQueue) TotalProcessed ΒΆ
TotalProcessed returns the total number of tasks that have been processed and dequeued.
func (*AnyQueue) YieldProgress ΒΆ
YieldProgress broadcasts a progress update to all subscribers.
type FileStore ΒΆ
type FileStore struct {
// contains filtered or unexported fields
}
FileStore provides persistent storage for retryable tasks. It manages task log files, compaction, and metadata tracking for tasks.
func NewFileStore ΒΆ
NewFileStore creates a new FileStore for the given file path. It rebuilds metadata from the existing log file if present.
func (*FileStore) CreateTask ΒΆ
func (fs *FileStore) CreateTask(task *RetryableTask) error
CreateTask appends a new retryable task to the log file and updates internal counters.
func (*FileStore) DeleteTask ΒΆ
func (*FileStore) GetLatestTask ΒΆ
func (fs *FileStore) GetLatestTask(taskID string) (*RetryableTask, error)
func (*FileStore) ReadDueTasks ΒΆ
func (fs *FileStore) ReadDueTasks() ([]*RetryableTask, error)
func (*FileStore) ReadTasks ΒΆ
func (fs *FileStore) ReadTasks() ([]*RetryableTask, error)
func (*FileStore) RebuildMetaData ΒΆ
RebuildMetaData scans the log file and rebuilds internal counters for tasks and deletions.
type JobErrorReturn ΒΆ
type JobErrorReturn struct {
ErrorObj error
ErrorString string `json:"error"` // Used for JSON serialization
RetryWorthy bool `json:"retry_worthy"`
}
JobErrorReturn contains error information from task execution JobErrorReturn holds error information for a failed job and implements custom JSON marshaling/unmarshaling to handle the error type
func (JobErrorReturn) MarshalJSON ΒΆ
func (j JobErrorReturn) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler interface
func (*JobErrorReturn) UnmarshalJSON ΒΆ
func (j *JobErrorReturn) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler interface
type OnMaxRetryHandler ΒΆ
OnMaxRetryHandler is a function that handles when a task reaches max retries
type PriorityQueue ΒΆ
type PriorityQueue []*RetryableTask
PriorityQueue implements heap.Interface and holds RetryableTasks
func (PriorityQueue) Len ΒΆ
func (pq PriorityQueue) Len() int
func (PriorityQueue) Less ΒΆ
func (pq PriorityQueue) Less(i, j int) bool
func (*PriorityQueue) Pop ΒΆ
func (pq *PriorityQueue) Pop() interface{}
func (*PriorityQueue) Push ΒΆ
func (pq *PriorityQueue) Push(x interface{})
func (PriorityQueue) Swap ΒΆ
func (pq PriorityQueue) Swap(i, j int)
type RateLimitEntry ΒΆ
type RateLimiter ΒΆ
type RateLimiter struct {
// contains filtered or unexported fields
}
func NewRateLimiter ΒΆ
func NewRateLimiter(storageDir string) *RateLimiter
func (*RateLimiter) CheckLimit ΒΆ
func (r *RateLimiter) CheckLimit(group string, maxPerMinute int) bool
CheckLimit returns true if the task is allowed to execute, false if it should be rate-limited
type RetryableTask ΒΆ
type RetryableTask struct {
TaskID string `json:"taskId"`
RetryCount int `json:"retryCount"`
MaxRetries int `json:"maxRetries"`
RetryAfterHours float64 `json:"retryAfterHours"`
RetryAfterTime time.Time `json:"retryAfterTime"`
TaskData string `json:"taskData"` // JSON string to store task-specific data
TaskType string `json:"taskType"` // For diagnostic purposes only
RateLimitGroup *string `json:"rate_limit_group,omitempty"`
MaxPerMinute *int `json:"max_per_minute,omitempty"`
AutoDedupe *bool `json:"autoDedupe,omitempty"`
PayloadHash *string `json:"payloadHash,omitempty"`
UrgencyScore *float64 `json:"urgency_score,omitempty"`
// Fields to store error information for OnMaxRetryReached
LastErrorObj error
LastJobError *JobErrorReturn
ExecuteAt time.Time `json:"executeAt"`
CronExpr *string `json:"cronExpression,omitempty"`
WebhookUrl *string `json:"webhookUrl,omitempty"`
MaxExecutionSeconds *int `json:"maxExecutionSeconds,omitempty"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `json:"deletedAt,omitempty"`
// Embedded task object - this is the actual task that will be executed
EmbeddedTask Task `json:"-"`
}
Task with retries
func CreateTaskWithPayload ΒΆ
func CreateTaskWithPayload[P any]( taskID string, taskType string, payload P, maxRetries int, retryAfterHours int, ) (*RetryableTask, error)
CreateTaskWithPayload creates a new task with the provided payload
func FetchDueTasks ΒΆ
func FetchDueTasks() ([]RetryableTask, error)
FetchDueTasks gets all tasks that are due for execution based on RetryAfter time
func (*RetryableTask) GenerateRandomString ΒΆ
func (t *RetryableTask) GenerateRandomString(length int) (string, error)
func (*RetryableTask) GetMaxRetries ΒΆ
func (t *RetryableTask) GetMaxRetries() int
func (*RetryableTask) GetRetryAfterHours ΒΆ
func (t *RetryableTask) GetRetryAfterHours() float64
func (*RetryableTask) GetRetryAfterTime ΒΆ
func (t *RetryableTask) GetRetryAfterTime() time.Time
func (*RetryableTask) GetRetryCount ΒΆ
func (t *RetryableTask) GetRetryCount() int
func (*RetryableTask) GetTaskID ΒΆ
func (t *RetryableTask) GetTaskID() string
func (*RetryableTask) MarshalJSON ΒΆ
func (t *RetryableTask) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface to ensure proper serialization of RetryableTask
func (*RetryableTask) UnmarshalJSON ΒΆ
func (t *RetryableTask) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface to properly deserialize a RetryableTask
func (*RetryableTask) UpdateTaskRetryConfig ΒΆ
func (t *RetryableTask) UpdateTaskRetryConfig(taskId string) error
UpdateTaskRetryConfig updates a task's retry configuration in the database
func (*RetryableTask) UpdateTaskRetryConfigWithError ΒΆ
func (t *RetryableTask) UpdateTaskRetryConfigWithError(taskId string, errorObj error) error
UpdateTaskRetryConfigWithError updates a task's retry configuration and stores error information
type SnerdTask ΒΆ
type SnerdTask struct {
// Core Task Identification
TaskID string `json:"taskId"` // Unique identifier for the task
// Retry Configuration
RetryCount int `json:"retryCount"` // Current retry count
MaxRetries int `json:"maxRetries"` // Maximum number of retries allowed
RetryAfterHours float64 `json:"retryAfterHours"` // Hours to wait before retrying
RetryAfterTime time.Time `json:"retryAfterTime"` // Timestamp for next retry attempt
// Task Execution Data
TaskType string `json:"taskType"` // Type of task (maps to registered handler)
Parameters string `json:"parameters"` // JSON-encoded parameters for the task
RateLimitGroup *string `json:"rate_limit_group,omitempty"`
MaxPerMinute *int `json:"max_per_minute,omitempty"`
AutoDedupe *bool `json:"autoDedupe,omitempty"`
PayloadHash *string `json:"payloadHash,omitempty"`
UrgencyScore *float64 `json:"urgency_score,omitempty"`
LastErrorObj error `json:"lastErrorObj"` // Last error that occurred
LastJobError *JobErrorReturn `json:"lastJobError"` // Detailed error information
ExecuteAt time.Time `json:"executeAt"`
CronExpr *string `json:"cronExpression,omitempty"`
WebhookUrl *string `json:"webhookUrl,omitempty"`
MaxExecutionSeconds *int `json:"maxExecutionSeconds,omitempty"`
// Timestamps for record-keeping
CreatedAt time.Time `json:"-"` // When the task was created
UpdatedAt time.Time `json:"-"` // When the task was last updated
DeletedAt *time.Time `json:"deletedAt,omitempty"` // Soft deletion timestamp
}
SnerdTask is a retryable task that stores parameters instead of implementations
func CreateTask ΒΆ
func CreateTask(taskID string, taskType string, parameters interface{}, maxRetries int, retryAfterHours float64) (*SnerdTask, error)
CreateTask is a convenience function that creates a new task with the given parameters. This is the simplified client API function for creating parameter-based tasks
func FromRetryableTask ΒΆ
func FromRetryableTask(rt *RetryableTask) *SnerdTask
FromRetryableTask creates a SnerdTask from a RetryableTask This is used when loading tasks from the file store
func NewSnerdTask ΒΆ
func NewSnerdTask( taskID string, taskType string, parameters interface{}, maxRetries int, retryAfterHours float64, ) (*SnerdTask, error)
NewSnerdTask creates a new task with the specified parameters
func NewSnerdTaskAdvanced ΒΆ
func NewSnerdTaskAdvanced( taskID string, taskType string, parameters interface{}, maxRetries int, retryAfterHours float64, rateLimitGroup *string, maxPerMinute *int, autoDedupe *bool, urgencyScore *float64, executeAtOpt *string, cronOpt *string, webhookUrl *string, maxExecutionSeconds *int, ) (*SnerdTask, error)
NewSnerdTaskAdvanced creates a new task with advanced parameters
func (*SnerdTask) GetMaxRetries ΒΆ
GetMaxRetries returns the maximum retry count
func (*SnerdTask) GetRetryAfterHours ΒΆ
GetRetryAfterHours returns the retry interval in hours
func (*SnerdTask) GetRetryAfterTime ΒΆ
GetRetryAfterTime returns the time when the task should be retried
func (*SnerdTask) GetRetryCount ΒΆ
GetRetryCount returns the current retry count
func (*SnerdTask) OnMaxRetryReached ΒΆ
func (*SnerdTask) ToRetryableTask ΒΆ
func (t *SnerdTask) ToRetryableTask() *RetryableTask
ToRetryableTask wraps the SnerdTask in a RetryableTask for storage compatibility
func (*SnerdTask) UpdateRetryConfig ΒΆ
UpdateRetryConfig updates the retry configuration after a failed execution
type Task ΒΆ
type Task interface {
// GetTaskID returns the unique identifier for the task.
GetTaskID() string
// GetRetryCount returns the number of times this task has been retried.
GetRetryCount() int
// Execute runs the task's logic. Return an error if the task fails and should be retried.
Execute(ctx context.Context) error
}
Task represents a unit of work that can be processed by the queue system.
type TaskFactory ΒΆ
TaskFactory creates a Task from its stored data. The factory function is responsible for reconstructing a Task instance, including unmarshaling any stored data.
func CreateTaskFactoryWithDecoder ΒΆ
func CreateTaskFactoryWithDecoder[P any](creator func(taskID string, payload P) Task) TaskFactory
CreateTaskFactoryWithDecoder creates a factory function that can reconstruct tasks from stored data This helps client code avoid having to deal with marshaling/unmarshaling
type TaskHandler ΒΆ
TaskHandler is a function that processes parameters to execute a task
type TaskWithData ΒΆ
type TaskWithData interface {
Task
// GetTaskType returns a unique identifier for this task type.
// This is used for debugging and monitoring, not for type-based dispatch.
GetTaskType() string
// MarshalData serializes the task data to JSON.
MarshalData() ([]byte, error)
// UnmarshalData deserializes the task data from JSON.
UnmarshalData([]byte) error
// Clone creates a new instance of this task with the same type but no data.
// This will be populated via UnmarshalData when reconstructing tasks.
Clone() TaskWithData
}
TaskWithData extends Task to support saving and retrieving task-specific data. Implement this interface if your task needs to persist additional fields.
type TaskWithMaxRetryCallback ΒΆ
type TaskWithMaxRetryCallback interface {
// OnMaxRetryReached is called when the task reaches its maximum retry count.
OnMaxRetryReached(ctx context.Context, contextProvider func() interface{}) error
}
TaskWithMaxRetryCallback allows a task to handle the case where it has reached its maximum number of retries.