taskqueue

package
v0.10.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

taskqueue

taskqueue defines provider-neutral task queue contracts. It is not a queue runtime and does not implement persistence, polling, acknowledgements, retries, dead-letter queues, locking, metrics, or distributed scheduler ownership.

Provider packages adapt these contracts to concrete systems such as Redis, cloud queues, or in-process workers.

Agent Quick Rules

  • Use TaskType as the semantic routing and schema identifier. Do not treat it as a provider topic, queue, stream, or storage key.
  • Use Queue only as an optional provider-facing lane name.
  • Create tasks with New for raw payload bytes, NewEncodedTask for any registered codec, NewJSONTask for JSON, or NewProtoTask for protobuf.
  • Treat JSON, protobuf, YAML, and TOML as payload codecs. The durable payload schema is the TaskType plus the registered Go payload factory, not the codec name.
  • Register exactly one Processor per TaskType on a Router.
  • Put provider execution metadata in context with ExecutionInfo; do not add it to payload schemas.
  • Use PeriodicTask only for recurring enqueue definitions: enqueue the same static Task envelope with the same enqueue policy on each schedule fire.
  • Do not use PeriodicTask for arbitrary scheduler callbacks, dynamic payload generation, distributed lock ownership, or workflow orchestration.
  • Validate provider-facing enqueue policy with EnqueueOptions.Validate().
  • For periodic tasks, do not use absolute enqueue timing such as WithProcessAt or WithDeadline; those values become stale when reused.

Consumer Shape

Define a task payload and register one processor for its semantic type:

type WelcomeEmail struct {
	UserID string `json:"user_id"`
}

router := taskqueue.NewRouter()
err := router.Register(taskqueue.NewProcessor("email.welcome", func(ctx context.Context, task taskqueue.Task) error {
	var payload WelcomeEmail
	if err := taskqueue.DecodeJSON(task, &payload); err != nil {
		return err
	}
	return sendWelcomeEmail(ctx, payload.UserID)
}))

Create an envelope at the application boundary. JSON is available as a convenience helper:

task, err := taskqueue.NewJSONTask(
	taskqueue.Definition{Type: "email.welcome", Queue: "mailers"},
	WelcomeEmail{UserID: "user-1"},
	taskqueue.WithKey("user-1"),
	taskqueue.WithHeader("trace-id", traceID),
)

For protobuf payloads, use NewProtoTask and DecodeProto. This works with message types generated by protoc-gen-go, including .pb.go files generated for ConnectRPC APIs; use the generated message type as the payload schema, not the .connect.go client or handler types.

task, err := taskqueue.NewProtoTask(
	taskqueue.Definition{Type: "email.welcome", Queue: "mailers"},
	&emailv1.WelcomeEmail{UserId: "user-1"},
	taskqueue.WithKey("user-1"),
)

Submit it through a provider adapter that implements Enqueuer:

err = enqueuer.Enqueue(ctx, task, taskqueue.WithMaxRetry(3), taskqueue.WithTimeout(time.Minute))

Schema Registry

Use SchemaRegistry when application code wants to map payload Go types to task definitions and decode tasks without hard-coding DTO allocation in worker code. The registry maps TaskType to payload schema factories; codec selection is supplied separately by NewTask, DecodeWithCodec, or the task envelope's PayloadCodec().

registry := taskqueue.NewSchemaRegistry()
err := registry.Register(taskqueue.Definition{Type: "email.welcome", Queue: "mailers"}, func() any {
	return &WelcomeEmail{}
})

task, err := registry.NewTask(taskqueue.JSONCodec, WelcomeEmail{UserID: "user-1"})
payload, err := registry.Decode(task)

Factories must return pointers. The registry rejects ambiguous mappings where one payload Go type is registered for multiple task types.

Protobuf uses the same registry and schema mapping:

registry := taskqueue.NewSchemaRegistry()
err := registry.Register(taskqueue.Definition{Type: "email.welcome", Queue: "mailers"}, func() any {
	return &emailv1.WelcomeEmail{}
})

task, err := registry.NewProtoTask(&emailv1.WelcomeEmail{UserId: "user-1"})
payload, err := registry.Decode(task)
welcome := payload.(*emailv1.WelcomeEmail)

NewJSONTask, DecodeJSON, SchemaRegistry.NewJSONTask, and SchemaRegistry.DecodeJSON remain available for explicit JSON callers. NewProtoTask, DecodeProto, SchemaRegistry.NewProtoTask, and SchemaRegistry.DecodeProto provide matching protobuf helpers. YAML and TOML are available through the codec-neutral NewEncodedTask, DecodePayloadWithCodec, SchemaRegistry.NewTask, and SchemaRegistry.DecodeWithCodec APIs using taskqueue.YAMLCodec, taskqueue.YMLCodec, or taskqueue.TOMLCodec.

Periodic Tasks

Periodic tasks are intentionally narrow. They describe a recurring enqueue, not a general timed job:

task, err := taskqueue.NewJSONTask(
	taskqueue.Definition{Type: "reports.generate_daily", Queue: "reports"},
	struct {
		Kind string `json:"kind"`
	}{Kind: "daily"},
	taskqueue.WithKey("reports:daily"),
)
schedule, err := taskqueue.CronSchedule("0 2 * * *", taskqueue.WithLocation("UTC"))
periodic, err := taskqueue.NewPeriodicTask(
	"reports.daily",
	schedule,
	task,
	taskqueue.WithMaxRetry(3),
	taskqueue.WithTimeout(2*time.Minute),
)

PeriodicTask.Name is the unique registration key for one registrar instance. Provider adapters should return ErrDuplicatePeriodicTask when the same name is registered twice in that instance.

CronSchedule validates only the portable five-field shape and optional IANA location. Provider adapters remain responsible for cron dialect details such as field ranges, names, and provider-specific extensions.

IntervalSchedule is duration-based and rejects timezone options.

Enqueue Policy

EnqueueOptions carries provider-neutral policy. Zero values mean provider defaults.

Supported policy:

  • WithDelay: request processing after a relative delay.
  • WithProcessAt: request processing at an absolute time.
  • WithMaxRetry: override provider retry count.
  • WithTimeout: bound one handling attempt.
  • WithDeadline: stop processing after an absolute deadline.
  • WithUnique: request provider duplicate suppression for a duration.

EnqueueOptions.Validate() rejects policies that cannot be interpreted consistently across providers:

  • negative delay
  • WithDelay and WithProcessAt together
  • negative max retry
  • negative timeout
  • negative unique TTL

PeriodicTask also rejects WithProcessAt and WithDeadline, because a reused absolute timestamp is not stable across repeated schedule fires.

Provider Adapter Guidance

Provider adapters should map these contracts to their own systems and document the behavior they own:

  • How TaskType, Queue, Key, Headers, PayloadCodec, and payload bytes are encoded.
  • How enqueue policy maps to provider options.
  • Whether WithUnique is supported and what fields define uniqueness.
  • How processor errors are retried, skipped, dead-lettered, or recorded.
  • What ErrSkipRetry means for that provider.
  • Whether processor registration is allowed after worker start.
  • Whether periodic task registration is startup-only or can be reconciled while running.
  • How duplicate periodic task registration is detected in one registrar instance.

The base package intentionally does not define cross-process duplicate prevention, distributed scheduler leadership, storage schemas, or acknowledgement semantics.

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

Examples

Constants

View Source
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

View Source
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

func DecodeJSON(task Task, target any) error

DecodeJSON decodes a JSON task payload into target.

func DecodePayload added in v0.10.3

func DecodePayload(task Task, target any) error

DecodePayload decodes task payload into target using task.PayloadCodec().

func DecodePayloadWithCodec added in v0.10.3

func DecodePayloadWithCodec(task Task, codecName string, target any) error

DecodePayloadWithCodec decodes task payload into target using codecName.

func DecodeProto added in v0.10.3

func DecodeProto(task Task, target any) error

DecodeProto decodes a protobuf task payload into target.

Types

type Definition

type Definition struct {
	Type  TaskType
	Queue string
}

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.

func Recover

func Recover() Middleware

Recover converts processor panics into ErrPanic.

type Option

type Option func(*taskConfig)

Option configures task metadata.

func WithHeader

func WithHeader(key, value string) Option

WithHeader adds one task metadata header.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders adds task metadata headers.

func WithKey

func WithKey(key string) Option

WithKey sets the task idempotency or ordering key.

func WithPayloadCodec added in v0.10.3

func WithPayloadCodec(codecName string) Option

WithPayloadCodec records the codec used to encode raw task payload bytes.

type PayloadResolver

type PayloadResolver interface {
	Resolve(TaskType) (any, error)
}

PayloadResolver allocates an empty payload target for a task type.

type PayloadResolverFunc

type PayloadResolverFunc func(TaskType) (any, error)

PayloadResolverFunc adapts a function into a PayloadResolver.

func (PayloadResolverFunc) Resolve

func (f PayloadResolverFunc) Resolve(taskType TaskType) (any, error)

Resolve calls f(taskType).

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

type Processor interface {
	TaskType() TaskType
	Process(context.Context, Task) error
}

Processor processes one task type.

func NewProcessor

func NewProcessor(taskType TaskType, fn ProcessorFunc) Processor

NewProcessor constructs a Processor for one task type.

type ProcessorFunc

type ProcessorFunc func(context.Context, Task) error

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

type Registrar interface {
	Register(Processor) error
}

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

func NewRouter

func NewRouter() *Router

NewRouter constructs an empty task router.

func (*Router) Process

func (r *Router) Process(ctx context.Context, task Task) error

Process dispatches task to the processor registered for task.Type().

func (*Router) Register

func (r *Router) Register(processor Processor) error

Register registers one processor for its non-empty task type.

type Runner

type Runner interface {
	Run(context.Context) error
}

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

func (s Schedule) Interval() time.Duration

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

func (s Schedule) Location() string

Location returns the configured IANA timezone name for cron schedules.

func (Schedule) Spec added in v0.9.5

func (s Schedule) Spec() string

Spec returns the cron expression for cron schedules.

func (Schedule) Validate added in v0.9.5

func (s Schedule) Validate() error

Validate checks whether the schedule carries enough information for a provider adapter to register it.

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

func (r *SchemaRegistry) NewTask(codecName string, payload any, opts ...Option) (Task, error)

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.

func (*SchemaRegistry) Resolve

func (r *SchemaRegistry) Resolve(taskType TaskType) (any, error)

Resolve returns a fresh payload target for taskType.

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

func NewEncodedTask(def Definition, codecName string, payload any, opts ...Option) (Task, error)

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) Headers

func (t Task) Headers() map[string]string

Headers returns a copy of task extension metadata.

func (Task) Key

func (t Task) Key() string

Key returns the task idempotency or ordering key.

func (Task) Payload

func (t Task) Payload() []byte

Payload returns a copy of the task payload bytes.

func (Task) PayloadCodec added in v0.10.3

func (t Task) PayloadCodec() string

PayloadCodec returns the codec used to encode payload bytes.

func (Task) Queue

func (t Task) Queue() string

Queue returns the provider queue lane name.

func (Task) Type

func (t Task) Type() TaskType

Type returns the semantic task contract type.

type TaskType

type TaskType string

TaskType is the semantic contract identifier for a task payload schema.

type Worker added in v0.9.4

type Worker interface {
	Start(context.Context) error
	Shutdown(context.Context) error
}

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL