Documentation
¶
Overview ¶
Package taskqueue defines transport-neutral task queue contracts.
It models background tasks as semantic Task values, plus provider-neutral capabilities for enqueueing, handler registration, middleware, worker lifecycle, and runtime loops. It intentionally does not define worker storage, acknowledgement, retry, dead-letter, or locking behavior. Periodic tasks in this package are recurring enqueue definitions: enqueue this static Task envelope with this enqueue policy on this schedule. Arbitrary scheduler callbacks, dynamic payload generation, and distributed execution ownership remain application or provider concerns. Provider adapters map these contracts to their own systems.
TaskType is a semantic contract identifier used for payload schema and processor routing. Queue is an optional provider-facing lane name. Payload codec identifies the byte encoding, such as JSON or protobuf, and is separate from the schema identified by TaskType. Providers decide how to encode TaskType, Queue, Key, Headers, PayloadCodec, payload bytes, and enqueue options into their own envelopes.
ExecutionInfo carries provider worker metadata for the current processing attempt through context; it does not change the task payload schema.
Index ¶
- Constants
- Variables
- func ContextWithExecutionInfo(ctx context.Context, info ExecutionInfo) context.Context
- func DecodeJSON(task Task, target any) error
- func DecodePayload(task Task, target any) error
- func DecodePayloadWithCodec(task Task, codecName string, target any) error
- func DecodeProto(task Task, target any) error
- type Definition
- type EnqueueOption
- func WithDeadline(deadline time.Time) EnqueueOption
- func WithDelay(delay time.Duration) EnqueueOption
- func WithMaxRetry(maxRetry int) EnqueueOption
- func WithProcessAt(processAt time.Time) EnqueueOption
- func WithTimeout(timeout time.Duration) EnqueueOption
- func WithUnique(ttl time.Duration) EnqueueOption
- type EnqueueOptions
- func (o EnqueueOptions) Deadline() time.Time
- func (o EnqueueOptions) Delay() time.Duration
- func (o EnqueueOptions) MaxRetry() (int, bool)
- func (o EnqueueOptions) ProcessAt() time.Time
- func (o EnqueueOptions) Timeout() time.Duration
- func (o EnqueueOptions) UniqueTTL() time.Duration
- func (o EnqueueOptions) Validate() error
- type Enqueuer
- type ExecutionInfo
- type ExecutionInfoOption
- type Middleware
- type Option
- type PayloadResolver
- type PayloadResolverFunc
- type PeriodicTask
- type PeriodicTaskRegistrar
- type PeriodicTaskScheduler
- type Processor
- type ProcessorFunc
- type Registrar
- type Router
- type Runner
- type Schedule
- type ScheduleKind
- type ScheduleOption
- type SchemaRegistry
- func (r *SchemaRegistry) Decode(task Task) (any, error)
- func (r *SchemaRegistry) DecodeJSON(task Task) (any, error)
- func (r *SchemaRegistry) DecodeProto(task Task) (any, error)
- func (r *SchemaRegistry) DecodeWithCodec(task Task, codecName string) (any, error)
- func (r *SchemaRegistry) DefinitionOf(payload any) (Definition, error)
- func (r *SchemaRegistry) NewJSONTask(payload any, opts ...Option) (Task, error)
- func (r *SchemaRegistry) NewProtoTask(payload any, opts ...Option) (Task, error)
- func (r *SchemaRegistry) NewTask(codecName string, payload any, opts ...Option) (Task, error)
- func (r *SchemaRegistry) Register(def Definition, factory func() any) error
- func (r *SchemaRegistry) Resolve(taskType TaskType) (any, error)
- type Task
- func New(def Definition, payload []byte, opts ...Option) (Task, error)
- func NewEncodedTask(def Definition, codecName string, payload any, opts ...Option) (Task, error)
- func NewJSONTask(def Definition, payload any, opts ...Option) (Task, error)
- func NewProtoTask(def Definition, payload any, opts ...Option) (Task, error)
- type TaskType
- type Worker
Examples ¶
Constants ¶
const ( // JSONCodec is the registered payload codec name for JSON task payloads. JSONCodec = "json" // ProtoCodec is the registered payload codec name for protobuf task payloads. ProtoCodec = "proto" // TOMLCodec is the registered payload codec name for TOML task payloads. TOMLCodec = "toml" // YAMLCodec is the registered payload codec name for YAML task payloads. YAMLCodec = "yaml" // YMLCodec is the registered payload codec alias for YAML task payloads. YMLCodec = "yml" )
Variables ¶
var ( ErrEmptyType = errors.New("task type is empty") ErrNilProcessor = errors.New("task processor is nil") ErrUnhandledType = errors.New("task type is unhandled") ErrDuplicateProcessor = errors.New("task processor is already registered") ErrDuplicatePayloadType = errors.New("task payload type is already registered") ErrUnknownType = errors.New("task type is unknown") ErrUnknownPayloadType = errors.New("task payload type is unknown") ErrEmptyPayloadCodec = errors.New("task payload codec is empty") ErrUnknownPayloadCodec = errors.New("task payload codec is unknown") ErrNilPayload = errors.New("task payload is nil") ErrNilDecodeTarget = errors.New("task decode target is nil") ErrNilPayloadFactory = errors.New("task payload factory is nil or returned nil") ErrInvalidPayloadFactory = errors.New("task payload factory returned invalid payload") ErrNilPayloadResolver = errors.New("task payload resolver is nil") ErrPanic = errors.New("task processor panicked") ErrInvalidEnqueueOption = errors.New("task enqueue option is invalid") ErrEmptySchedule = errors.New("task schedule is empty") ErrInvalidSchedule = errors.New("task schedule is invalid") ErrInvalidScheduleLocation = errors.New("task schedule location is invalid") ErrInvalidScheduleOption = errors.New("task schedule option is invalid") ErrEmptyPeriodicTaskName = errors.New("periodic task name is empty") ErrInvalidPeriodicTaskPolicy = errors.New("periodic task enqueue policy is invalid") ErrDuplicatePeriodicTask = errors.New("periodic task is already registered") // ErrSkipRetry marks a failure as non-retryable for provider adapters. ErrSkipRetry = errors.New("skip retry for task") )
Functions ¶
func ContextWithExecutionInfo ¶ added in v0.9.4
func ContextWithExecutionInfo(ctx context.Context, info ExecutionInfo) context.Context
ContextWithExecutionInfo stores execution metadata in ctx.
func DecodeJSON ¶
DecodeJSON decodes a JSON task payload into target.
func DecodePayload ¶ added in v0.10.3
DecodePayload decodes task payload into target using task.PayloadCodec().
func DecodePayloadWithCodec ¶ added in v0.10.3
DecodePayloadWithCodec decodes task payload into target using codecName.
func DecodeProto ¶ added in v0.10.3
DecodeProto decodes a protobuf task payload into target.
Types ¶
type Definition ¶
Definition identifies a semantic task type and optional queue lane.
type EnqueueOption ¶
type EnqueueOption func(*EnqueueOptions)
EnqueueOption configures transport-neutral enqueue policy.
func WithDeadline ¶
func WithDeadline(deadline time.Time) EnqueueOption
WithDeadline asks the provider to stop processing the task after deadline.
func WithDelay ¶
func WithDelay(delay time.Duration) EnqueueOption
WithDelay asks the provider to process the task after delay.
func WithMaxRetry ¶
func WithMaxRetry(maxRetry int) EnqueueOption
WithMaxRetry asks the provider to override its default retry count.
func WithProcessAt ¶
func WithProcessAt(processAt time.Time) EnqueueOption
WithProcessAt asks the provider to process the task at processAt.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) EnqueueOption
WithTimeout asks the provider to bound one handling attempt by timeout.
func WithUnique ¶
func WithUnique(ttl time.Duration) EnqueueOption
WithUnique asks the provider to suppress duplicates for ttl when supported.
type EnqueueOptions ¶
type EnqueueOptions struct {
// contains filtered or unexported fields
}
EnqueueOptions carries transport-neutral enqueue policy.
func NewEnqueueOptions ¶
func NewEnqueueOptions(opts ...EnqueueOption) EnqueueOptions
NewEnqueueOptions applies opts and returns the resulting enqueue policy.
func (EnqueueOptions) Deadline ¶
func (o EnqueueOptions) Deadline() time.Time
Deadline returns the absolute processing deadline.
func (EnqueueOptions) Delay ¶
func (o EnqueueOptions) Delay() time.Duration
Delay returns the relative processing delay.
func (EnqueueOptions) MaxRetry ¶
func (o EnqueueOptions) MaxRetry() (int, bool)
MaxRetry returns the configured retry count and whether it was explicitly set.
func (EnqueueOptions) ProcessAt ¶
func (o EnqueueOptions) ProcessAt() time.Time
ProcessAt returns the absolute processing time.
func (EnqueueOptions) Timeout ¶
func (o EnqueueOptions) Timeout() time.Duration
Timeout returns the per-attempt timeout.
func (EnqueueOptions) UniqueTTL ¶
func (o EnqueueOptions) UniqueTTL() time.Duration
UniqueTTL returns the provider duplicate suppression window.
func (EnqueueOptions) Validate ¶ added in v0.10.2
func (o EnqueueOptions) Validate() error
Validate checks whether the enqueue policy is internally consistent.
Zero values mean the provider default. Delay and ProcessAt are alternative ways to describe initial processing time and must not both be set.
type Enqueuer ¶
type Enqueuer interface {
Enqueue(context.Context, Task, ...EnqueueOption) error
}
Enqueuer hands a task to a task queue provider.
type ExecutionInfo ¶ added in v0.9.4
type ExecutionInfo struct {
// contains filtered or unexported fields
}
ExecutionInfo carries provider worker metadata for the current processing attempt. It is not part of the task payload schema.
func ExecutionInfoFromContext ¶ added in v0.9.4
func ExecutionInfoFromContext(ctx context.Context) (ExecutionInfo, bool)
ExecutionInfoFromContext returns execution metadata from ctx when present.
func NewExecutionInfo ¶ added in v0.9.4
func NewExecutionInfo(opts ...ExecutionInfoOption) ExecutionInfo
NewExecutionInfo applies opts and returns execution metadata.
func (ExecutionInfo) MaxRetry ¶ added in v0.9.4
func (i ExecutionInfo) MaxRetry() (int, bool)
MaxRetry returns the provider retry cap and whether it was supplied.
func (ExecutionInfo) Queue ¶ added in v0.9.4
func (i ExecutionInfo) Queue() string
Queue returns the provider queue lane.
func (ExecutionInfo) RetryCount ¶ added in v0.9.4
func (i ExecutionInfo) RetryCount() (int, bool)
RetryCount returns the provider retry count and whether it was supplied.
func (ExecutionInfo) TaskID ¶ added in v0.9.4
func (i ExecutionInfo) TaskID() string
TaskID returns the provider task identifier.
type ExecutionInfoOption ¶ added in v0.9.4
type ExecutionInfoOption func(*ExecutionInfo)
ExecutionInfoOption configures execution metadata.
func WithExecutionMaxRetry ¶ added in v0.9.4
func WithExecutionMaxRetry(maxRetry int) ExecutionInfoOption
WithExecutionMaxRetry records the provider retry cap for this task.
func WithExecutionQueue ¶ added in v0.9.4
func WithExecutionQueue(queue string) ExecutionInfoOption
WithExecutionQueue records the provider queue lane for this attempt.
func WithExecutionRetryCount ¶ added in v0.9.4
func WithExecutionRetryCount(retryCount int) ExecutionInfoOption
WithExecutionRetryCount records how many prior attempts have failed.
func WithExecutionTaskID ¶ added in v0.9.4
func WithExecutionTaskID(taskID string) ExecutionInfoOption
WithExecutionTaskID records the provider task identifier for this attempt.
type Middleware ¶
type Middleware func(ProcessorFunc) ProcessorFunc
Middleware wraps a task processor function.
func Logging ¶
func Logging(logger *slog.Logger) Middleware
Logging records task processor start, success, and failure events with slog.
type Option ¶
type Option func(*taskConfig)
Option configures task metadata.
func WithHeader ¶
WithHeader adds one task metadata header.
func WithHeaders ¶
WithHeaders adds task metadata headers.
func WithPayloadCodec ¶ added in v0.10.3
WithPayloadCodec records the codec used to encode raw task payload bytes.
type PayloadResolver ¶
PayloadResolver allocates an empty payload target for a task type.
type PayloadResolverFunc ¶
PayloadResolverFunc adapts a function into a PayloadResolver.
type PeriodicTask ¶ added in v0.9.5
type PeriodicTask struct {
// contains filtered or unexported fields
}
PeriodicTask describes a recurring enqueue definition for a concrete task.
Each schedule fire enqueues the same Task envelope with the same enqueue policy. Dynamic payload generation belongs in application or provider-level orchestration outside this transport-neutral contract. This intentionally narrow core shape is name + Schedule + Task + EnqueuePolicy.
func NewPeriodicTask ¶ added in v0.9.5
func NewPeriodicTask(name string, schedule Schedule, task Task, opts ...EnqueueOption) (PeriodicTask, error)
NewPeriodicTask constructs a periodic task producer contract.
Example ¶
package main
import (
"fmt"
"time"
"github.com/go-jimu/components/taskqueue"
)
func main() {
task, err := taskqueue.NewJSONTask(
taskqueue.Definition{Type: "reports.generate_daily", Queue: "reports"},
struct {
Kind string `json:"kind"`
}{Kind: "daily"},
taskqueue.WithKey("reports:daily"),
)
if err != nil {
panic(err)
}
schedule, err := taskqueue.CronSchedule("0 2 * * *", taskqueue.WithLocation("UTC"))
if err != nil {
panic(err)
}
periodic, err := taskqueue.NewPeriodicTask(
"reports.daily",
schedule,
task,
taskqueue.WithMaxRetry(3),
taskqueue.WithTimeout(2*time.Minute),
)
if err != nil {
panic(err)
}
fmt.Println(periodic.Name(), periodic.Schedule().Kind(), periodic.Task().Type())
}
Output: reports.daily cron reports.generate_daily
func (PeriodicTask) EnqueuePolicy ¶ added in v0.9.5
func (t PeriodicTask) EnqueuePolicy() EnqueueOptions
EnqueuePolicy returns the enqueue policy for scheduled enqueues.
func (PeriodicTask) Name ¶ added in v0.9.5
func (t PeriodicTask) Name() string
Name returns the semantic name of the periodic task producer.
func (PeriodicTask) Schedule ¶ added in v0.9.5
func (t PeriodicTask) Schedule() Schedule
Schedule returns when the task should be enqueued.
func (PeriodicTask) Task ¶ added in v0.9.5
func (t PeriodicTask) Task() Task
Task returns the task envelope to enqueue.
func (PeriodicTask) Validate ¶ added in v0.9.5
func (t PeriodicTask) Validate() error
Validate checks whether a periodic task has a semantic identity, schedule, routable task type, and enqueue policy suitable for repeated scheduled enqueues.
type PeriodicTaskRegistrar ¶ added in v0.9.5
type PeriodicTaskRegistrar interface {
RegisterPeriodicTask(PeriodicTask) error
}
PeriodicTaskRegistrar registers periodic task producers.
PeriodicTask.Name is the unique registration key for one registrar instance. Implementations should return ErrDuplicatePeriodicTask when the same name is registered twice in that instance. Cross-process or cross-replica duplicate prevention is outside this provider-neutral contract. Implementations should document whether registration is only supported before Start or can be reconciled while running.
type PeriodicTaskScheduler ¶ added in v0.9.6
type PeriodicTaskScheduler interface {
PeriodicTaskRegistrar
Worker
}
PeriodicTaskScheduler registers periodic task producers and exposes the provider lifecycle used by application runtime hooks.
This is only a provider-neutral capability composition. It does not define how schedules are compiled, persisted, locked, or executed by a provider.
type Processor ¶
Processor processes one task type.
func NewProcessor ¶
func NewProcessor(taskType TaskType, fn ProcessorFunc) Processor
NewProcessor constructs a Processor for one task type.
type ProcessorFunc ¶
ProcessorFunc adapts a function to task processing middleware.
func Chain ¶
func Chain(processor ProcessorFunc, middleware ...Middleware) ProcessorFunc
Chain wraps processor with middleware in declaration order.
type Registrar ¶
Registrar registers task processors.
Register is a processor registration operation only. It does not imply that a provider worker has started polling, acknowledged tasks, scheduled retries, or joined a runtime process.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router registers processors by task type and dispatches tasks.
Example ¶
package main
import (
"context"
"fmt"
"github.com/go-jimu/components/taskqueue"
)
type welcomeEmail struct {
UserID string `json:"user_id"`
}
func main() {
router := taskqueue.NewRouter()
if err := router.Register(taskqueue.NewProcessor("email.welcome", func(_ context.Context, task taskqueue.Task) error {
var payload welcomeEmail
if err := taskqueue.DecodeJSON(task, &payload); err != nil {
return err
}
fmt.Println(task.Type(), task.Queue(), payload.UserID)
return nil
})); err != nil {
panic(err)
}
task, err := taskqueue.NewJSONTask(
taskqueue.Definition{Type: "email.welcome", Queue: "mailers"},
welcomeEmail{UserID: "user-1"},
taskqueue.WithKey("user-1"),
)
if err != nil {
panic(err)
}
if err := router.Process(context.Background(), task); err != nil {
panic(err)
}
}
Output: email.welcome mailers user-1
type Runner ¶
Runner is an optional runtime loop capability for providers that actively consume tasks.
Run should start consuming tasks and block until ctx is done or startup fails. Context cancellation is a normal shutdown signal: implementations should stop accepting new work, gracefully drain in-flight tasks when supported, and return nil unless startup or shutdown itself fails.
type Schedule ¶ added in v0.9.5
type Schedule struct {
// contains filtered or unexported fields
}
Schedule describes when a recurring task enqueue should happen.
func CronSchedule ¶ added in v0.9.5
func CronSchedule(spec string, opts ...ScheduleOption) (Schedule, error)
CronSchedule constructs a validated standard five-field cron schedule shape.
Validation is intentionally limited to the portable five-field shape and optional IANA location. Provider adapters remain responsible for cron dialect details such as value ranges and named fields.
func IntervalSchedule ¶ added in v0.9.5
func IntervalSchedule(interval time.Duration, opts ...ScheduleOption) (Schedule, error)
IntervalSchedule constructs a validated fixed interval schedule.
Interval schedules are duration-based; use CronSchedule with WithLocation when wall-clock timezone semantics matter.
func (Schedule) Interval ¶ added in v0.9.5
Interval returns the interval for fixed interval schedules.
func (Schedule) Kind ¶ added in v0.9.5
func (s Schedule) Kind() ScheduleKind
Kind returns the schedule kind.
func (Schedule) Location ¶ added in v0.9.5
Location returns the configured IANA timezone name for cron schedules.
type ScheduleKind ¶ added in v0.9.5
type ScheduleKind string
ScheduleKind identifies the provider-neutral form of a periodic schedule.
const ( // ScheduleKindCron represents a cron expression schedule. ScheduleKindCron ScheduleKind = "cron" // ScheduleKindInterval represents a fixed interval schedule. ScheduleKindInterval ScheduleKind = "interval" )
type ScheduleOption ¶ added in v0.9.5
type ScheduleOption func(*scheduleConfig)
ScheduleOption configures a schedule.
func WithLocation ¶ added in v0.9.5
func WithLocation(location string) ScheduleOption
WithLocation sets an IANA timezone name for cron schedules.
Fixed interval schedules are duration-based and reject location options.
type SchemaRegistry ¶
type SchemaRegistry struct {
// contains filtered or unexported fields
}
SchemaRegistry maps semantic task types to Go payload schemas.
Example ¶
package main
import (
"fmt"
"github.com/go-jimu/components/taskqueue"
)
type welcomeEmail struct {
UserID string `json:"user_id"`
}
func main() {
registry := taskqueue.NewSchemaRegistry()
if err := registry.Register(taskqueue.Definition{Type: "email.welcome", Queue: "mailers"}, func() any {
return &welcomeEmail{}
}); err != nil {
panic(err)
}
task, err := registry.NewJSONTask(welcomeEmail{UserID: "user-1"})
if err != nil {
panic(err)
}
decoded, err := registry.DecodeJSON(task)
if err != nil {
panic(err)
}
payload := decoded.(*welcomeEmail)
fmt.Println(task.Type(), payload.UserID)
}
Output: email.welcome user-1
Example (Proto) ¶
package main
import (
"fmt"
testdata "github.com/go-jimu/components/encoding/testdata"
"github.com/go-jimu/components/taskqueue"
)
func main() {
registry := taskqueue.NewSchemaRegistry()
if err := registry.Register(taskqueue.Definition{Type: "model.index", Queue: "indexers"}, func() any {
return &testdata.TestModel{}
}); err != nil {
panic(err)
}
task, err := registry.NewProtoTask(&testdata.TestModel{Id: 7, Name: "doc-7"})
if err != nil {
panic(err)
}
decoded, err := registry.Decode(task)
if err != nil {
panic(err)
}
payload := decoded.(*testdata.TestModel)
fmt.Println(task.Type(), task.PayloadCodec(), payload.Id, payload.Name)
}
Output: model.index proto 7 doc-7
func NewSchemaRegistry ¶
func NewSchemaRegistry() *SchemaRegistry
NewSchemaRegistry creates an empty schema registry.
func (*SchemaRegistry) Decode ¶ added in v0.10.3
func (r *SchemaRegistry) Decode(task Task) (any, error)
Decode resolves task.Type() and decodes task payload into that schema.
func (*SchemaRegistry) DecodeJSON ¶
func (r *SchemaRegistry) DecodeJSON(task Task) (any, error)
DecodeJSON resolves task.Type() and decodes a JSON task payload into that schema.
func (*SchemaRegistry) DecodeProto ¶ added in v0.10.3
func (r *SchemaRegistry) DecodeProto(task Task) (any, error)
DecodeProto resolves task.Type() and decodes a protobuf task payload into that schema.
func (*SchemaRegistry) DecodeWithCodec ¶ added in v0.10.3
func (r *SchemaRegistry) DecodeWithCodec(task Task, codecName string) (any, error)
DecodeWithCodec resolves task.Type() and decodes task payload with codecName.
func (*SchemaRegistry) DefinitionOf ¶
func (r *SchemaRegistry) DefinitionOf(payload any) (Definition, error)
DefinitionOf returns the task definition registered for payload's Go type.
func (*SchemaRegistry) NewJSONTask ¶
func (r *SchemaRegistry) NewJSONTask(payload any, opts ...Option) (Task, error)
NewJSONTask creates a JSON task using the definition registered for payload.
func (*SchemaRegistry) NewProtoTask ¶ added in v0.10.3
func (r *SchemaRegistry) NewProtoTask(payload any, opts ...Option) (Task, error)
NewProtoTask creates a protobuf task using the definition registered for payload.
func (*SchemaRegistry) NewTask ¶ added in v0.10.3
NewTask creates an encoded task using the definition registered for payload.
func (*SchemaRegistry) Register ¶
func (r *SchemaRegistry) Register(def Definition, factory func() any) error
Register associates a task definition with a factory for its payload schema.
type Task ¶
type Task struct {
// contains filtered or unexported fields
}
Task is a provider-neutral background task envelope.
func New ¶
func New(def Definition, payload []byte, opts ...Option) (Task, error)
New constructs a task from raw payload bytes.
func NewEncodedTask ¶ added in v0.10.3
NewEncodedTask constructs a task by encoding payload with a registered codec.
func NewJSONTask ¶
func NewJSONTask(def Definition, payload any, opts ...Option) (Task, error)
NewJSONTask constructs a task by JSON-encoding payload.
func NewProtoTask ¶ added in v0.10.3
func NewProtoTask(def Definition, payload any, opts ...Option) (Task, error)
NewProtoTask constructs a task by protobuf-encoding payload.
func (Task) Definition ¶
func (t Task) Definition() Definition
Definition returns the task definition.
func (Task) PayloadCodec ¶ added in v0.10.3
PayloadCodec returns the codec used to encode payload bytes.
type TaskType ¶
type TaskType string
TaskType is the semantic contract identifier for a task payload schema.
type Worker ¶ added in v0.9.4
Worker is an optional lifecycle capability for provider workers managed by application runtime hooks.
Start should begin accepting tasks and return after startup succeeds or fails. Shutdown should stop accepting new tasks and wait for in-flight tasks to finish until ctx is done.