faktotum

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2024 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Faktotum

A Go package that wraps the Faktory job processing system. Provides type-safe handlers, hook support, and integrates with modular Go applications.

Go Reference Go Report Card

Features

  • Type-safe job handlers using Go generics
  • Global and per-job hooks for job lifecycle management
  • Connection pooling for job operations
  • Structured logging with slog
  • Parallel job enqueueing

Installation

go get github.com/patrickward/faktotum

Prerequisites

This package requires a running Faktory server. For server installation and management, see Faktory Installation.

Faktory Server Configuration

The following are some common server configuration options as defined in the Faktory wiki, but view the source for the most up-to-date information.

Default server ports:

  • 7419: Main server port for job processing
  • 7420: Web UI interface

Configure the Faktory server connection using environment variables:

# Server connection
FAKTORY_URL=tcp://localhost:7419      # Server address
FAKTORY_PROVIDER=FAKTORY_URL          # Alternate env var containing server URL
FAKTORY_PASSWORD=your-password        # Server password

The CLI can also accept these options:

Faktory 1.8.0                                                                                                                       │
Copyright © 2024 Contributed Systems LLC                                                                                            │
Licensed under the GNU Affero Public License 3.0                                                                                    │
-b [binding]    Network binding (use :7419 to listen on all interfaces), default: localhost:7419                                    │
-w [binding]    Web UI binding (use :7420 to listen on all interfaces), default: localhost:7420                                     │
-e [env]        Set environment (development, staging, production), default: development                                            │
-l [level]      Set logging level (error, warn, info, debug), default: info                                                         │
-v              Show version and license information                                                                                │
-h              This help screen

If you make the web UI available and a password is set, the UI will use Basic Authentication with the FAKTORY_PASSWORD value.

Only expose the Faktory server and UI to trusted networks.

See the Faktory Security Guide and any reported vulnerabilities for more information.

Basic Usage

package main

import (
    "context"
    "log/slog"
    "time"
    
    "github.com/patrickward/faktotum"
)

// Define a job payload

type EmailJob struct {
    To      string
    Subject string
    Body    string
}

func main() {
    // Create and initialize Faktotum
    f := faktotum.New(faktotum.DefaultConfig())
    if err := f.Init(); err != nil {
        panic(err)
    }
    
    // Create a type-safe handler
    handler := faktotum.NewTypedHandler(func(ctx context.Context, job EmailJob) error {
        return sendEmail(job)
    })
    
    // Register the handler
    f.RegisterJob("send_email", handler.Perform)
    
    // Start processing
    ctx := context.Background()
    if err := f.Start(ctx); err != nil {
        panic(err)
    }
    
    // Create and enqueue a job
    job := faktotum.NewJob("send_email", EmailJob{
        To:      "user@example.com",
        Subject: "Hello",
        Body:    "World",
    }).
        Queue("critical").
        Retry(3).
        Build()
    
    if err := f.EnqueueJob(ctx, job); err != nil {
        slog.Error("Failed to enqueue job", "error", err)
    }
}

Configuration

config := &faktotum.Config{
    WorkerCount:     5,                             // Concurrent workers
    Queues:          []string{"default", "high"},   // Queues to process
    QueueWeights:    map[string]int{                // Optional weights
        "default": 1,
        "high":    10,
    },
    Labels:          []string{"api"},               // Optional worker labels
    ShutdownTimeout: 30 * time.Second,              // Shutdown timeout
    Logger:          slog.Default(),                // Logger
}

Creating Jobs

Use the job builder to configure jobs:

job := faktotum.NewJob("job_type", payload).
    Queue("high").              // Queue name
    Retry(3).                   // Retry attempts
    Schedule(time.Now().Add(1 * time.Hour)). // Future execution
    ReserveFor(5 * time.Minute).    // Reservation timeout
    Backtrace(20).              // Backtrace line count
    Custom(map[string]interface{}{
        "customer_id": "12345",
    }).
    Build()

Hooks

Hooks can be registered globally or per job type:

type MetricsHook struct {
    successCount uint64
    failureCount uint64
}

func (h *MetricsHook) BeforeJob(ctx context.Context, job *faktory.Job) error {
    // Pre-job processing
    return nil
}

func (h *MetricsHook) AfterJob(ctx context.Context, job *faktory.Job, err error) {
    // Post-job processing
}

// Register globally - runs for all jobs
f.RegisterGlobalHook("metrics", &MetricsHook{})

// Register for specific job type - runs only for "email" jobs
f.RegisterJobHook("email", "metrics", &MetricsHook{})

Hooks execute in this order:

  1. Global hooks in registration order
  2. Job-specific hooks in registration order

Module System Integration

Why does it require ID(), Init(), Start(), and Stop() methods?

This package is designed to be used with my web application framework, which uses a modular approach to registering and managing the lifecycle of components/services. However, it can be used independently of the framework.

Faktotum implements these interfaces:

type Module interface {
    ID() string
    Init() error
}

type StartupModule interface {
    Module
    Start(ctx context.Context) error
}

type ShutdownModule interface {
    Module
    Stop(ctx context.Context) error
}

An example usage with a module system:

app.RegisterModule(faktotum.New(config))

The module system would call the appropriate methods when the application starts and stops.

Testing

You can mock the client factory to test Faktotum without connecting to a Faktory server.

The following example uses the github.com/stretchr/testify/mock package:

// Create mock client
type mockClient struct {
    mock.Mock
}

func (m *mockClient) Push(job *faktory.Job) error {
    args := m.Called(job)
    return args.Error(0)
}

func (m *mockClient) Close() {
    m.Called()
}

func (m *mockClient) Cleanup() {
    m.Called()
}

func setupNewFactotum(c *mockClient, config *faktotum.Config) *faktotum.Faktotum {
    return faktotum.New(config, faktotum.WithClientFactory(func() (faktotum.Client, error) {
        return c, nil
    }))
}

Job Scheduling

Faktotum includes optional periodic scheduling capabilities built on go-co-op/gocron.

You can enable scheduling when creating your Faktotum instance using the WithScheduler option:

f := faktotum.New(
    faktotumConfig,
    faktotum.WithScheduler(&faktotum.SchedulerConfig{
        Name:     "app-scheduler",
        Location: time.UTC,
    }),
)

// Use the scheduler if enabled
if scheduler := f.Scheduler(); scheduler != nil {
    err := scheduler.ScheduleDaily(
        "cleanup-job",
        faktotum.NewJob("cleanup", nil).Build(),
        1,
        gocron.NewAtTimes(gocron.NewAtTime(3, 0, 0)),
    )
}

See SCHEDULER.md for more documentation on scheduling patterns and options.

Documentation

Index

Constants

View Source
const (
	AttrJobID      = "job_id"
	AttrJobType    = "job_type"
	AttrError      = "error"
	AttrQueueName  = "queue"
	AttrRetryCount = "retry_count"
)

Common attribute keys for consistency

Variables

This section is empty.

Functions

This section is empty.

Types

type BulkEnqueueResult

type BulkEnqueueResult struct {
	JobID string
	Error error
}

BulkEnqueueResult represents the result of a bulk enqueue operation

type Client

type Client interface {
	// Push enqueues a job
	Push(job *faktory.Job) error

	// Close closes the client
	Close()

	// Cleanup cleans up the client
	Cleanup()
}

Client defines the interface for job operations. It is a wrapper around the Faktory client, so that we can mock it later.

type ClientFactory

type ClientFactory func() (Client, error)

ClientFactory defines a function that creates a new Client and a cleanup function

type Config

type Config struct {
	// Logger is the logger to use
	Logger *slog.Logger
	// WorkerCount is the number of concurrent workers
	WorkerCount int
	// Queues are the queues to process, in order of precedence
	Queues []string
	// QueueWeights maps queue names to their weights (optional). If provided, the worker will process queues in weighted order.
	// If not provided, the worker will process queues in strict order.
	QueueWeights map[string]int
	// Labels to attach to this worker pool
	Labels []string
	// ShutdownTimeout is how long to wait for jobs to finish during shutdown
	ShutdownTimeout time.Duration
}

Config holds configuration for the Faktory worker module

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration

type FaktoryLogger

type FaktoryLogger struct {
	// contains filtered or unexported fields
}

FaktoryLogger is a logger that implements the Logger interface from the faktory_worker package. It wraps the slog.Logger type from the slog package.

func NewFaktoryLogger

func NewFaktoryLogger(logger *slog.Logger) *FaktoryLogger

NewFaktoryLogger creates a new FaktoryLogger.

func (*FaktoryLogger) Debug

func (l *FaktoryLogger) Debug(v ...interface{})

Debug logs a message at the debug level.

func (*FaktoryLogger) Debugf

func (l *FaktoryLogger) Debugf(format string, args ...interface{})

Debugf logs a message at the debug level with a format string.

func (*FaktoryLogger) Error

func (l *FaktoryLogger) Error(v ...interface{})

Error logs a message at the error level.

func (*FaktoryLogger) Errorf

func (l *FaktoryLogger) Errorf(format string, args ...interface{})

Errorf logs a message at the error level with a format string.

func (*FaktoryLogger) Fatal

func (l *FaktoryLogger) Fatal(v ...interface{})

Fatal logs a message at the fatal level and exits the program.

func (*FaktoryLogger) Fatalf

func (l *FaktoryLogger) Fatalf(format string, args ...interface{})

Fatalf logs a message at the fatal level with a format string and exits the program.

func (*FaktoryLogger) Info

func (l *FaktoryLogger) Info(v ...interface{})

Info logs a message at the info level.

func (*FaktoryLogger) Infof

func (l *FaktoryLogger) Infof(format string, args ...interface{})

Infof logs a message at the info level with a format string.

func (*FaktoryLogger) Warn

func (l *FaktoryLogger) Warn(v ...interface{})

Warn logs a message at the warn level.

func (*FaktoryLogger) Warnf

func (l *FaktoryLogger) Warnf(format string, args ...interface{})

Warnf logs a message at the warn level with a format string.

type Faktotum

type Faktotum struct {
	// contains filtered or unexported fields
}

Faktotum implements the Module interfaces for Faktory worker integration

func New

func New(cfg *Config, opts ...Option) *Faktotum

New creates a new Faktotum with the given configuration

func (*Faktotum) BulkEnqueue

func (f *Faktotum) BulkEnqueue(_ context.Context, jobs []*faktory.Job) []BulkEnqueueResult

BulkEnqueue enqueues multiple jobs in parallel

func (*Faktotum) EnqueueJob

func (f *Faktotum) EnqueueJob(_ context.Context, job *faktory.Job) error

EnqueueJob pushes a job to Faktory

func (*Faktotum) GetGlobalHooks

func (f *Faktotum) GetGlobalHooks() map[string]Hook

GetGlobalHooks returns all global hooks

func (*Faktotum) GetJobTypeHooks

func (f *Faktotum) GetJobTypeHooks(jobType string) map[string]Hook

GetJobTypeHooks returns all hooks for a specific job type

func (*Faktotum) ID

func (f *Faktotum) ID() string

ID implements Module interface

func (*Faktotum) Init

func (f *Faktotum) Init() error

Init implements Module interface

func (*Faktotum) RegisterGlobalHook

func (f *Faktotum) RegisterGlobalHook(name string, hook Hook) error

RegisterGlobalHook adds a new hook

func (*Faktotum) RegisterJob

func (f *Faktotum) RegisterJob(jobType string, handler worker.Perform)

RegisterJob registers a job handler with hooks and panic recovery

func (*Faktotum) RegisterJobHook

func (f *Faktotum) RegisterJobHook(jobType, name string, hook Hook) error

RegisterJobHook adds a new hook for a specific job type

func (*Faktotum) Scheduler added in v0.0.2

func (f *Faktotum) Scheduler() *Scheduler

Scheduler returns the scheduler, if one is configured. If no scheduler is configured, this will return nil.

This method is safe for concurrent access.

The scheduler is not started automatically. It must be started by the caller and added via the WithScheduler option.

If no scheduler is configured, this will return nil. The caller should check for nil before using the scheduler.

Example:

if s := m.Scheduler(); s != nil {
	s.ScheduleDaily("my-job", "0 0 * * *", myJobHandler)
}

func (*Faktotum) Start

func (f *Faktotum) Start(ctx context.Context) error

Start implements StartupModule interface and starts the Faktory worker

func (*Faktotum) Stop

func (f *Faktotum) Stop(_ context.Context) error

Stop implements ShutdownModule interface and stops the Faktory worker

func (*Faktotum) UnregisterGlobalHook

func (f *Faktotum) UnregisterGlobalHook(name string) error

UnregisterGlobalHook removes a global hook

func (*Faktotum) UnregisterJobHook

func (f *Faktotum) UnregisterJobHook(jobType string, name string) error

UnregisterJobHook removes a job-specific hook

func (*Faktotum) WrapWithHooks

func (f *Faktotum) WrapWithHooks(jobType string, handler worker.Perform) worker.Perform

WrapWithHooks wraps a job handler with hook processing and logging

func (*Faktotum) WrapWithPanicRecovery

func (f *Faktotum) WrapWithPanicRecovery(jobType string, handler worker.Perform) worker.Perform

WrapWithPanicRecovery wraps a job handler with panic recovery

type Hook

type Hook interface {
	BeforeJob(ctx context.Context, job *faktory.Job) error
	AfterJob(ctx context.Context, job *faktory.Job, err error)
}

Hook defines the interface for job processing hooks

type HookRegistry

type HookRegistry struct {
	// contains filtered or unexported fields
}

HookRegistry manages both global and job-specific hooks

func NewHookRegistry

func NewHookRegistry() *HookRegistry

NewHookRegistry creates a new hook registry

func (*HookRegistry) GetGlobalHooks

func (r *HookRegistry) GetGlobalHooks() map[string]Hook

GetGlobalHooks returns a copy of the global hooks map

func (*HookRegistry) GetHooks

func (r *HookRegistry) GetHooks(jobType string) []Hook

GetHooks returns all hooks that should run for a job

func (*HookRegistry) GetJobTypeHooks

func (r *HookRegistry) GetJobTypeHooks(jobType string) map[string]Hook

GetJobTypeHooks returns a copy of the hooks map for a specific job type

func (*HookRegistry) RegisterGlobalHook

func (r *HookRegistry) RegisterGlobalHook(name string, hook Hook) error

RegisterGlobalHook adds a hook that runs for all jobs

func (*HookRegistry) RegisterJobHook

func (r *HookRegistry) RegisterJobHook(jobType string, name string, hook Hook) error

RegisterJobHook adds a hook for a specific job type

func (*HookRegistry) UnregisterGlobalHook

func (r *HookRegistry) UnregisterGlobalHook(name string) error

UnregisterGlobalHook removes a global hook by name

func (*HookRegistry) UnregisterJobHook

func (r *HookRegistry) UnregisterJobHook(jobType string, name string) error

UnregisterJobHook removes a job-specific hook

type Job added in v0.0.2

type Job faktory.Job

type JobBuilder

type JobBuilder struct {
	// contains filtered or unexported fields
}

JobBuilder provides a fluent interface for building Faktory jobs

func NewJob

func NewJob(jobType string, args ...interface{}) *JobBuilder

NewJob creates a new JobBuilder with the given job type and arguments

func (*JobBuilder) Backtrace

func (b *JobBuilder) Backtrace(lines int) *JobBuilder

Backtrace sets the number of backtrace lines to retain on errors

func (*JobBuilder) Build

func (b *JobBuilder) Build() *faktory.Job

Build returns the configured Faktory job

func (*JobBuilder) Custom

func (b *JobBuilder) Custom(data map[string]interface{}) *JobBuilder

Custom sets custom metadata for the job

func (*JobBuilder) Queue

func (b *JobBuilder) Queue(queue string) *JobBuilder

Queue sets the job queue

func (*JobBuilder) ReserveFor

func (b *JobBuilder) ReserveFor(duration time.Duration) *JobBuilder

ReserveFor sets how long the job should be reserved for (in seconds)

func (*JobBuilder) Retry

func (b *JobBuilder) Retry(count int) *JobBuilder

Retry sets the number of times to retry the job Use 0 for no retries, -1 for infinite retries

func (*JobBuilder) Schedule

func (b *JobBuilder) Schedule(at time.Time) *JobBuilder

Schedule sets when the job should be executed

type LoggingHook

type LoggingHook struct {
	// contains filtered or unexported fields
}

LoggingHook implements Hook to provide logging of job execution

func NewLoggingHook

func NewLoggingHook(logger *log.Logger) *LoggingHook

func (*LoggingHook) AfterJob

func (h *LoggingHook) AfterJob(ctx context.Context, job *faktory.Job, err error)

func (*LoggingHook) BeforeJob

func (h *LoggingHook) BeforeJob(ctx context.Context, job *faktory.Job) error

type MetricsHook

type MetricsHook struct {
	// contains filtered or unexported fields
}

MetricsHook implements Hook to collect metrics about job execution

func (*MetricsHook) AfterJob

func (h *MetricsHook) AfterJob(ctx context.Context, job *faktory.Job, err error)

func (*MetricsHook) BeforeJob

func (h *MetricsHook) BeforeJob(ctx context.Context, job *faktory.Job) error

func (*MetricsHook) GetStats

func (h *MetricsHook) GetStats() (success uint64, failure uint64, avgDuration time.Duration)

type NilPayloadError

type NilPayloadError struct{}

NilPayloadError represents an error when a nil payload is received

func (*NilPayloadError) Error

func (e *NilPayloadError) Error() string

type Option

type Option func(module *Faktotum)

Option represents a functional option for configuring the Faktotum

func WithClientFactory

func WithClientFactory(factory ClientFactory) Option

WithClientFactory allows injection of a custom client creation function

func WithScheduler added in v0.0.2

func WithScheduler(config SchedulerConfig) Option

WithScheduler adds a scheduler to the Faktotum

type PanicError

type PanicError struct {
	Value   any
	Stack   []byte
	Context string
}

PanicError is returned when a panic occurs during job execution

func (*PanicError) Error

func (e *PanicError) Error() string

type ScheduleOptions

type ScheduleOptions struct {
	Name        string
	Job         *faktory.Job
	Schedule    string // Cron expression
	WithSeconds bool   // Whether the cron expression includes seconds
	JobOptions  []gocron.JobOption
}

ScheduleOptions holds options for scheduling a job

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler manages periodic job scheduling for Faktotum

func NewScheduler

func NewScheduler(f *Faktotum, cfg *SchedulerConfig) (*Scheduler, error)

NewScheduler creates a new Scheduler

func (*Scheduler) ID

func (s *Scheduler) ID() string

ID returns the scheduler ID and implements the module interface for hop.

func (*Scheduler) Init

func (s *Scheduler) Init() error

Init initializes the scheduler. This implements the module interface for hop. It's a no-op for the scheduler.

func (*Scheduler) ListJobs

func (s *Scheduler) ListJobs() []string

ListJobs returns all scheduled job names, validating against the scheduler

func (*Scheduler) Schedule

func (s *Scheduler) Schedule(opts ScheduleOptions) error

Schedule schedules a job using a cron expression

func (*Scheduler) ScheduleDaily

func (s *Scheduler) ScheduleDaily(name string, job *faktory.Job, interval uint, atTimes gocron.AtTimes, options ...gocron.JobOption) error

ScheduleDaily schedules a job to run daily at specific times

func (*Scheduler) ScheduleEvery

func (s *Scheduler) ScheduleEvery(name string, job *faktory.Job, duration time.Duration, options ...gocron.JobOption) error

ScheduleEvery schedules a job to run at a fixed duration

func (*Scheduler) ScheduleMonthly

func (s *Scheduler) ScheduleMonthly(name string, job *faktory.Job, interval uint, daysOfTheMonth gocron.DaysOfTheMonth, atTimes gocron.AtTimes, options ...gocron.JobOption) error

ScheduleMonthly schedules a job to run monthly on specific days and times

func (*Scheduler) ScheduleWeekly

func (s *Scheduler) ScheduleWeekly(name string, job *faktory.Job, interval uint, daysOfTheWeek gocron.Weekdays, atTimes gocron.AtTimes, options ...gocron.JobOption) error

ScheduleWeekly schedules a job to run weekly on specific days and times

func (*Scheduler) Start

func (s *Scheduler) Start(ctx context.Context) error

Start starts the scheduler

func (*Scheduler) Stop

func (s *Scheduler) Stop(_ context.Context) error

Stop stops the scheduler

func (*Scheduler) Unschedule

func (s *Scheduler) Unschedule(name string) error

type SchedulerConfig

type SchedulerConfig struct {
	Name     string
	Location *time.Location
}

SchedulerConfig holds configuration for the scheduler

func DefaultSchedulerConfig

func DefaultSchedulerConfig() *SchedulerConfig

DefaultSchedulerConfig returns the default scheduler configuration

type TypedHandler

type TypedHandler[T any] struct {
	// contains filtered or unexported fields
}

TypedHandler helps create type-safe job handlers

func NewTypedHandler

func NewTypedHandler[T any](handler func(context.Context, T) error) *TypedHandler[T]

NewTypedHandler creates a new typed handler

func (*TypedHandler[T]) Perform

func (th *TypedHandler[T]) Perform(ctx context.Context, args ...any) error

Perform implements the faktory_worker.Perform type.

Jump to

Keyboard shortcuts

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