perago

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 24 Imported by: 0

README

Laravel's queues for Go: jobs, workers, retries, middleware, chains, batches and failed jobs,
on any SQL database, Redis, Amazon SQS and Beanstalkd. Works with migro, never requires it.

CI Go reference MIT license Documentation


perago brings Laravel Queues to Go. Each job is a struct with a Handle method. You dispatch it to a connection, and a worker runs it with Laravel's semantics for tries, backoff, timeouts, unique and encrypted jobs, rate limiting, chains, batches, failed jobs and queue:* commands. It ships with test fakes too. The database driver needs nothing but database/sql, so it works on PostgreSQL, CockroachDB, Redshift, MySQL, MariaDB, SQLite, SQL Server and Oracle with whatever driver you already use; on a migro project, the perago/migro module plugs it into your *migro.DB, migrations and models.

Install

Go 1.25+.

go get github.com/LouisRiverstone/perago@latest
go install github.com/LouisRiverstone/perago/cmd/perago@latest

perago is split into modules, so you only download what you use. The core has no dependencies at all, and migro is optional: perago is compatible with it but never requires it. Add perago/migro only on a project that already uses migro (Using with migro).

Module go get Brings in
core github.com/LouisRiverstone/perago nothing: the standard library only. Jobs, workers, chains, batches, middleware, queuetest, console, the database driver and stores (database/sql)
Redis github.com/LouisRiverstone/perago/redis go-redis
SQS github.com/LouisRiverstone/perago/sqs AWS SDK v2 (SQS)
DynamoDB github.com/LouisRiverstone/perago/dynamodb AWS SDK v2 (DynamoDB)
Beanstalkd github.com/LouisRiverstone/perago/beanstalkd go-beanstalk
migro github.com/LouisRiverstone/perago/migro migro: Connect, migrations, model.Of

A quick look

Generate a job and the queue tables (.sql files, or migro migrations on a migro project):

perago make:job ProcessPodcast
perago make:queue-table --dialect=postgres && perago make:queue-failed-table && perago make:queue-batches-table && perago make:cache-table
// app/jobs/process_podcast.go
type ProcessPodcast struct {
	perago.Queueable
	PodcastID int64
}

func init() { perago.Register(&ProcessPodcast{}) }

func (j *ProcessPodcast) Tries() int                { return 5 }
func (j *ProcessPodcast) Backoff() []time.Duration  { return []time.Duration{10 * time.Second, time.Minute} }
func (j *ProcessPodcast) Middleware() []perago.Middleware {
	return []perago.Middleware{middleware.WithoutOverlapping(j.PodcastID)}
}

func (j *ProcessPodcast) Handle(ctx context.Context) error {
	// ... the error you return is retried with backoff until Tries runs out
	return nil
}

Configure the connections once, the way config/queue.php does. Redis is optional: the queue, the cache, failed jobs and batches can all live in your SQL database, and the worker can run inside your own process, so your app and its database are enough.

sqlDB, _ := sql.Open("pgx", os.Getenv("DATABASE_URL")) // any database/sql driver
db, _ := database.New(sqlDB, "postgres")                // or peragomigro.Connect(migroDB)

m, err := perago.New(perago.Config{
	Default: "database",
	Connections: map[string]perago.Connection{
		"database": {Driver: database.NewDriver(db, database.DriverOptions{RetryAfter: 90 * time.Second}), AfterCommit: true},
		"redis":    {Driver: redis.NewDriver(rdb, redis.DriverOptions{BlockFor: 5 * time.Second})},
		"sync":     {Driver: perago.SyncDriver()},
	},
	Failed:  database.NewFailedJobStore(db, ""),
	Batches: database.NewBatchStore(db, ""),
	Cache:   redis.NewCache(rdb, ""),           // unique jobs, locks, rate limits, worker signals
})

Dispatch:

m.Dispatch(&ProcessPodcast{PodcastID: podcast.ID}).OnQueue("podcasts").Delay(10 * time.Minute).Send(ctx)

m.Chain(&OptimizePodcast{}, &ReleasePodcast{}).Catch(func(ctx context.Context, err error) { ... }).Dispatch(ctx)

batch, _ := m.Batch(&ImportCsv{Rows: "1-100"}, &ImportCsv{Rows: "101-200"}).
	Then(func(ctx context.Context, b *perago.Batch) { ... }).
	AllowFailures().Dispatch(ctx)

Run workers like artisan queue:work, with an app console that embeds console.App:

perago queue:work redis --queue=high,default --tries=3 --timeout=60 --max-jobs=1000
perago queue:failed
perago queue:retry all
perago queue:monitor redis:default --max=100

Test without a queue:

fake := queuetest.Fake(m)
service.Publish(ctx, podcast)
queuetest.AssertPushed(t, fake, func(j *ProcessPodcast) bool { return j.PodcastID == podcast.ID })

What you get

  • Drivers: database (database/sql on PostgreSQL, CockroachDB, Redshift, MySQL, MariaDB, SQLite, SQL Server, Oracle), Redis (single, Sentinel, Cluster), SQS (FIFO, fair queues, overflow storage), Beanstalkd, sync, deferred, background, failover, null and an in-memory queue
  • Jobs: tries, backoff, timeouts, RetryUntil/RetryFor, max exceptions, fail on timeout, Failed hooks, manual Release/Delete/Fail, unique and unique-until-processing jobs, debounced jobs, encrypted jobs with key rotation, migro models serialized as keys (perago/migro/model)
  • Middleware: RateLimited, WithoutOverlapping, ThrottlesExceptions, FailOnException, Skip, Release, SkipIfBatchCancelled, plus Redis variants
  • Dispatching: delays, DispatchSync, after-response, bulk, PrepareForDispatch, after-commit transactions, queue routing and forwarding, closures
  • Chains and batches: catch callbacks, prepend/append to chain, batches inside chains, then/catch/finally/progress, adding jobs, cancelling, allowFailures, retrying failed batch jobs, pruning, and DynamoDB storage
  • Workers: priorities, --once, --stop-when-empty, --max-jobs, --max-time, --memory, --rest, queue:restart, queue:pause/queue:resume, graceful signals with Interruptible jobs, queue:listen
  • Failed jobs: database, DynamoDB or disabled; queue:failed, queue:retry, queue:retry-batch, queue:forget, queue:flush, queue:prune-failed
  • Events and monitoring: every Laravel queue event, Before/After/Failing/Looping, and queue:monitor with QueueBusy
  • Testing: Fake, FakeFor, FakeExcept with every Queue::/Bus:: assertion, and fake job interactions and batches

Documentation

https://louisriverstone.github.io/perago/

Contributing

Issues and pull requests are welcome. Read CONTRIBUTING.md first.

License

MIT

Documentation

Overview

Package perago is Laravel's queue system for Go: jobs, dispatching, delays, retries, middleware, unique and encrypted jobs, chains, batches, failed jobs, workers and test fakes, over the database (every migro dialect), Redis, SQS and Beanstalkd.

m, _ := perago.New(perago.Config{
	Default: "database",
	Connections: map[string]perago.Connection{
		"database": {Driver: database.NewDriver(db, database.DriverOptions{})},
		"sync":     {Driver: perago.SyncDriver()},
	},
	Failed:  database.NewFailedJobStore(db, ""),
	Batches: database.NewBatchStore(db, ""),
	Cache:   database.NewCache(db, ""),
})
_, err := m.Dispatch(&ProcessPodcast{PodcastID: 1}).OnQueue("podcasts").Send(ctx)

Index

Constants

View Source
const (
	ExitSuccess     = 0
	ExitError       = 1
	ExitMemoryLimit = 12
)

Worker exit statuses (queue:work exit codes).

Variables

View Source
var (
	ErrConnectionNotFound     = &Error{Code: ConnectionNotFound}
	ErrJobNotRegistered       = &Error{Code: JobNotRegistered}
	ErrClosureNotSerializable = &Error{Code: ClosureNotSerializable}
	ErrJobTimeout             = &Error{Code: JobTimeout}
	ErrMaxAttemptsExceeded    = &Error{Code: MaxAttemptsExceeded}
	ErrMaxExceptionsExceeded  = &Error{Code: MaxExceptionsExceeded}
	ErrBatchNotFound          = &Error{Code: BatchNotFound}
	ErrFailedJobNotFound      = &Error{Code: FailedJobNotFound}
	ErrModelNotFound          = &Error{Code: ModelNotFound}
	ErrNotInJob               = &Error{Code: NotInJob}
)

Sentinels for errors.Is.

Functions

func BindRuntime

func BindRuntime(ctx context.Context, rt *Runtime) context.Context

BindRuntime returns ctx carrying rt, as the worker passes it to Handle (queuetest uses it).

func DisplayNameOf

func DisplayNameOf(job any) string

DisplayNameOf is DisplayName() when declared, else NameOf.

func ErrorFrom

func ErrorFrom(ctx context.Context) error

ErrorFrom returns the error a failure callback (chain Catch, batch Catch) was called for.

func IsCode

func IsCode(err error, code Code) bool

IsCode reports whether err is a perago error with code.

func Listen

func Listen[E any](m *Manager, fn func(ctx context.Context, e E)) (off func())

Listen subscribes fn to events of type E and returns the unsubscribe function.

perago.Listen(m, func(ctx context.Context, e perago.JobFailed) { log.Println(e.Err) })

func NameOf

func NameOf(job any) string

NameOf is the name a job travels under: JobName() when declared, the registered name for its type, or "package.Type".

func NewFakeBatch

func NewFakeBatch(id, name string) (*Batch, *BatchRecorder)

NewFakeBatch returns a batch that only records Add, Cancel and Delete.

func NewUUID

func NewUUID() string

NewUUID returns a random version 4 UUID (drivers use it for job ids).

func Register

func Register(prototype Job)

Register makes a job type known to the workers under NameOf(prototype). Call it from init().

func init() { perago.Register(&ProcessPodcast{}) }

func RegisterAs

func RegisterAs(name string, prototype Job)

RegisterAs registers a job under an explicit name, for example to keep old payloads working after a rename.

func RegisterClosure

func RegisterClosure(name string, fn func(ctx context.Context, args json.RawMessage) error)

RegisterClosure registers a named function that any worker can run with Call.

func RegisterFactory

func RegisterFactory(name string, factory Factory)

RegisterFactory registers a job built by factory, so the worker can hand it dependencies:

perago.RegisterFactory("emails.Send", func() perago.Job { return &SendEmail{Mailer: mailer} })

Registering the same name twice replaces the factory.

func Registered

func Registered() []string

Registered lists every registered job name, sorted.

func RouteInterface

func RouteInterface[I any](m *Manager, connection, queue string)

RouteInterface routes every job implementing I.

func WithDeferred

func WithDeferred(ctx context.Context) (context.Context, func())

WithDeferred opens a scope for deferred jobs: they run when the returned flush is called.

Types

type AgeReporter

type AgeReporter interface {
	OldestPending(ctx context.Context, queue string) (time.Time, error)
}

AgeReporter knows when the oldest pending job was created (zero when none), for queue:monitor.

type Batch

type Batch struct {
	ID           string
	Name         string
	TotalJobs    int
	PendingJobs  int
	FailedJobs   int
	FailedJobIDs []string
	Options      BatchOptions
	CreatedAt    time.Time
	CancelledAt  *time.Time
	FinishedAt   *time.Time
	// contains filtered or unexported fields
}

Batch is a stored job batch (Illuminate\Bus\Batch).

func BatchFrom

func BatchFrom(ctx context.Context) *Batch

BatchFrom returns the batch a batch callback (Then, Catch, Finally, Progress) was called for.

func (*Batch) Add

func (b *Batch) Add(ctx context.Context, items ...any) error

Add queues more jobs on the batch, typically from one of its jobs. Items are Job values or []Job chains.

func (*Batch) Cancel

func (b *Batch) Cancel(ctx context.Context) error

Cancel cancels the batch; its jobs should check Cancelled (or use middleware.SkipIfBatchCancelled).

func (*Batch) Cancelled

func (b *Batch) Cancelled() bool

Cancelled reports whether the batch was cancelled.

func (*Batch) Delete

func (b *Batch) Delete(ctx context.Context) error

Delete removes the batch record.

func (*Batch) Finished

func (b *Batch) Finished() bool

Finished reports whether every job has run successfully.

func (*Batch) Fresh

func (b *Batch) Fresh(ctx context.Context) (*Batch, error)

Fresh reloads the batch from the store.

func (*Batch) HasFailures

func (b *Batch) HasFailures() bool

HasFailures reports whether a job failed.

func (*Batch) HasPendingJobs

func (b *Batch) HasPendingJobs() bool

HasPendingJobs reports whether jobs are still waiting.

func (*Batch) MarshalJSON

func (b *Batch) MarshalJSON() ([]byte, error)

MarshalJSON renders the batch like Laravel's Batch::toArray, so it can be returned from an HTTP handler as is.

func (*Batch) ProcessedJobs

func (b *Batch) ProcessedJobs() int

ProcessedJobs is how many jobs have run (successfully or not).

func (*Batch) Progress

func (b *Batch) Progress() int

Progress is the completion percentage, 0 to 100.

type BatchDispatched

type BatchDispatched struct{ Batch *Batch }

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type BatchOptions

type BatchOptions struct {
	Connection    string            `json:"connection,omitempty"`
	Queue         string            `json:"queue,omitempty"`
	AllowFailures bool              `json:"allowFailures,omitempty"`
	Then          []json.RawMessage `json:"then,omitempty"`
	Catch         []json.RawMessage `json:"catch,omitempty"`
	Finally       []json.RawMessage `json:"finally,omitempty"`
	Progress      []json.RawMessage `json:"progress,omitempty"`

	// Chain is the rest of a chain that contains this batch: it runs once the batch finishes
	// without being cancelled.
	Chain           []json.RawMessage `json:"chain,omitempty"`
	ChainConnection string            `json:"chainConnection,omitempty"`
	ChainQueue      string            `json:"chainQueue,omitempty"`
	ChainCatch      []json.RawMessage `json:"chainCatch,omitempty"`
}

BatchOptions is what a batch stores besides its counters: where its jobs go and its callbacks (encoded callback jobs).

type BatchRecorder

type BatchRecorder struct {
	Added     []any
	Cancelled bool
	Deleted   bool
}

BatchRecorder records what a job does to a fake batch (queuetest.WithFakeBatch).

type BatchStore

type BatchStore interface {
	Store(ctx context.Context, b *Batch) error
	// Find returns ErrBatchNotFound when the batch does not exist.
	Find(ctx context.Context, id string) (*Batch, error)
	// List returns batches newest first, up to limit, older than the batch id before ("" = newest).
	List(ctx context.Context, limit int, before string) ([]*Batch, error)
	IncrementTotalJobs(ctx context.Context, id string, n int) error
	// RecordSuccess decrements the pending jobs, drops jobID from the failed ids and returns the
	// updated batch.
	RecordSuccess(ctx context.Context, id, jobID string) (*Batch, error)
	// RecordFailure increments the failed jobs, records jobID and returns the updated batch.
	RecordFailure(ctx context.Context, id, jobID string) (*Batch, error)
	MarkFinished(ctx context.Context, id string, at time.Time) error
	Cancel(ctx context.Context, id string, at time.Time) error
	Delete(ctx context.Context, id string) error
	// Prune deletes finished batches finished before t.
	Prune(ctx context.Context, before time.Time) (int64, error)
	// PruneUnfinished deletes unfinished batches created before t.
	PruneUnfinished(ctx context.Context, before time.Time) (int64, error)
	// PruneCancelled deletes cancelled batches cancelled before t.
	PruneCancelled(ctx context.Context, before time.Time) (int64, error)
}

BatchStore persists batches (Laravel's BatchRepository).

type BulkPusher

type BulkPusher interface {
	PushBulk(ctx context.Context, ms []Message) ([]string, error)
}

BulkPusher pushes many messages in one round trip (Bus::bulk).

type Cache

type Cache interface {
	Get(ctx context.Context, key string) (value string, ok bool, err error)
	Put(ctx context.Context, key, value string, ttl time.Duration) error
	// Add stores value only when key is absent or expired, atomically, and reports whether it did.
	Add(ctx context.Context, key, value string, ttl time.Duration) (bool, error)
	// Increment adds by to the integer at key, creating it with ttl when absent.
	Increment(ctx context.Context, key string, by int64, ttl time.Duration) (int64, error)
	Forget(ctx context.Context, key string) error
	// ForgetIf deletes key only while it holds value (releasing a lock its owner holds).
	ForgetIf(ctx context.Context, key, value string) (bool, error)
}

Cache is the atomic key/value store behind unique jobs, debouncing, WithoutOverlapping, rate limiting, queue:restart and queue:pause. A ttl of 0 never expires. Implementations: NewMemoryCache (one process), database.NewCache and redis.NewCache.

type Closer

type Closer interface{ Close() error }

Closer releases driver resources when the Manager closes.

type Code

type Code string

Code is a stable, machine-readable error identifier.

const (
	InvalidConfig          Code = "INVALID_CONFIG"
	ConnectionNotFound     Code = "CONNECTION_NOT_FOUND"
	JobNotRegistered       Code = "JOB_NOT_REGISTERED"
	PayloadInvalid         Code = "PAYLOAD_INVALID"
	PayloadDecryptFailed   Code = "PAYLOAD_DECRYPT_FAILED"
	ClosureNotSerializable Code = "CLOSURE_NOT_SERIALIZABLE"
	PushFailed             Code = "PUSH_FAILED"
	PopFailed              Code = "POP_FAILED"
	DriverFailed           Code = "DRIVER_FAILED"
	JobFailedManually      Code = "JOB_FAILED_MANUALLY"
	JobTimeout             Code = "JOB_TIMEOUT"
	MaxAttemptsExceeded    Code = "MAX_ATTEMPTS_EXCEEDED"
	MaxExceptionsExceeded  Code = "MAX_EXCEPTIONS_EXCEEDED"
	BatchNotFound          Code = "BATCH_NOT_FOUND"
	BatchFailed            Code = "BATCH_FAILED"
	FailedJobNotFound      Code = "FAILED_JOB_NOT_FOUND"
	StoreFailed            Code = "STORE_FAILED"
	CacheFailed            Code = "CACHE_FAILED"
	FailoverExhausted      Code = "FAILOVER_EXHAUSTED"
	ModelNotFound          Code = "MODEL_NOT_FOUND"
	NotInJob               Code = "NOT_IN_JOB"
)

func CodeOf

func CodeOf(err error) Code

CodeOf extracts the perago Code from err, or "" when err is not a perago error.

type Config

type Config struct {
	// Default names the connection used when a job does not pick one. Defaults to the
	// PERAGO_CONNECTION or QUEUE_CONNECTION environment variable, then "sync".
	Default     string
	Connections map[string]Connection

	// Failed stores failed jobs; nil disables failed job storage (Laravel's "null" driver).
	Failed FailedJobStore
	// Batches stores job batches; nil makes Batch().Dispatch fail with INVALID_CONFIG.
	Batches BatchStore
	// Cache backs unique jobs, debouncing, overlap locks, rate limiters, queue:restart and
	// queue:pause. nil uses an in-process MemoryCache, enough for a single process only.
	Cache Cache
	// Key is the 32-byte AES-256 key for ShouldBeEncrypted jobs.
	Key []byte
	// PreviousKeys still decrypt jobs queued before a key rotation (APP_PREVIOUS_KEYS).
	PreviousKeys [][]byte

	Logger *slog.Logger
	Now    func() time.Time
}

Config configures New.

type Connection

type Connection struct {
	Driver Driver
	// Queue is the default queue name ("default").
	Queue string
	// AfterCommit holds every dispatch made inside a Manager.Transaction until it commits.
	AfterCommit bool
}

Connection is one entry of Laravel's config/queue.php connections.

type CountsCrashes

type CountsCrashes struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (CountsCrashes) CountCrashesAsExceptions

func (CountsCrashes) CountCrashesAsExceptions() bool

type DeletesMissingModels

type DeletesMissingModels struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (DeletesMissingModels) DeleteWhenMissingModels

func (DeletesMissingModels) DeleteWhenMissingModels() bool

type Dispatched

type Dispatched struct {
	Job           Job
	Connection    string
	Queue         string
	Delay         time.Duration
	Chain         []any
	Sync          bool
	AfterResponse bool
}

Dispatched describes a dispatch to an Interceptor.

type Driver

type Driver interface {
	Push(ctx context.Context, m Message) (id string, err error)
	// Pop reserves the next available job, or returns nil, nil when the queue is empty.
	Pop(ctx context.Context, queue string) (Reserved, error)
	// Size counts every job of the queue: pending, delayed and reserved.
	Size(ctx context.Context, queue string) (int64, error)
	// Clear deletes every job of the queue and returns how many were deleted.
	Clear(ctx context.Context, queue string) (int64, error)
}

Driver is a queue backend (Laravel's Queue contract).

func BackgroundDriver

func BackgroundDriver() Driver

BackgroundDriver runs each job in its own goroutine (the background driver). Manager.Wait and Manager.Close wait for them.

func DeferredDriver

func DeferredDriver() Driver

DeferredDriver runs jobs in this process after the current request (the deferred driver): when the dispatch context carries a scope from WithDeferred or Manager.Middleware, at the end of that scope; otherwise right away in a background goroutine.

func FailoverDriver

func FailoverDriver(connections ...string) Driver

FailoverDriver pushes to the first connection that accepts the job (the failover driver), emitting QueueFailedOver for each one that fails. Run a worker per underlying connection.

func Null

func Null() Driver

Null discards every job (the null driver).

func SyncDriver

func SyncDriver() Driver

SyncDriver runs each job immediately in the dispatching goroutine (the sync driver). A failing job's error is returned to the caller.

type Encrypted

type Encrypted struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (Encrypted) ShouldBeEncrypted

func (Encrypted) ShouldBeEncrypted()

type Error

type Error struct {
	Code    Code
	Message string
	Err     error
}

Error is the single error type returned across perago boundaries. Match with errors.Is(err, perago.ErrMaxAttemptsExceeded) or perago.CodeOf.

func Newf

func Newf(code Code, format string, args ...any) *Error

Newf builds an *Error without a cause.

func Wrap

func Wrap(code Code, cause error, format string, args ...any) *Error

Wrap builds an *Error around a cause.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches on Code so sentinels work with errors.Is.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Factory

type Factory func() Job

Factory builds an empty job ready for json.Unmarshal; use it to inject dependencies that are not part of the payload (fields tagged `json:"-"`).

type FailedJob

type FailedJob struct {
	ID         string // the job UUID
	Connection string
	Queue      string
	Payload    []byte
	Exception  string
	FailedAt   time.Time
}

FailedJob is a row of failed_jobs.

type FailedJobStore

type FailedJobStore interface {
	Log(ctx context.Context, f FailedJob) error
	// All returns every failed job, newest first.
	All(ctx context.Context) ([]FailedJob, error)
	// Find returns ErrFailedJobNotFound when the id is unknown.
	Find(ctx context.Context, id string) (*FailedJob, error)
	// IDs lists the failed job ids, of queue only when queue is not empty.
	IDs(ctx context.Context, queue string) ([]string, error)
	Forget(ctx context.Context, id string) (bool, error)
	// Flush deletes every failed job, or only those older than olderThan when it is positive.
	Flush(ctx context.Context, olderThan time.Duration) (int64, error)
	// Prune deletes the failed jobs that failed before t.
	Prune(ctx context.Context, before time.Time) (int64, error)
}

FailedJobStore persists failed jobs (Laravel's FailedJobProvider).

type FailsOnTimeout

type FailsOnTimeout struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (FailsOnTimeout) FailOnTimeout

func (FailsOnTimeout) FailOnTimeout() bool

type Hits

type Hits struct {
	Cache Cache
	Now   func() time.Time
}

Hits is a cache-backed hit counter with a decay window (Laravel's RateLimiter).

func (Hits) AvailableIn

func (h Hits) AvailableIn(ctx context.Context, key string) (time.Duration, error)

AvailableIn is how long until the window of key closes.

func (Hits) Clear

func (h Hits) Clear(ctx context.Context, key string) error

Clear resets key.

func (Hits) Hit

func (h Hits) Hit(ctx context.Context, key string, decay time.Duration) (int64, error)

Hit counts one hit, opening a window of decay when there is none.

func (Hits) TooManyAttempts

func (h Hits) TooManyAttempts(ctx context.Context, key string, max int) (bool, error)

TooManyAttempts reports whether key has used max hits in its current window.

type InProcess

type InProcess interface{ InProcess() bool }

InProcess is implemented by drivers whose jobs never leave the process (MemoryDriver), so they can carry closures.

type Interceptor

type Interceptor interface {
	InterceptDispatch(ctx context.Context, d Dispatched) bool
	InterceptBatch(ctx context.Context, b *PendingBatch) (*Batch, bool)
}

Interceptor captures dispatches before they reach a driver; queuetest installs one. Returning false lets the dispatch through.

type Interruptible

type Interruptible interface {
	Interrupted(sig os.Signal)
}

Interruptible jobs are told when the worker running them receives SIGTERM, SIGINT or SIGQUIT, so they can stop early; the worker still waits for Handle to return.

type Job

type Job interface {
	Handle(ctx context.Context) error
}

Job is a unit of background work. Its exported fields are its payload: they are JSON-encoded on dispatch and decoded into a fresh value, built by the registered factory, before Handle runs.

A job opts into Laravel's per-job settings by declaring the matching method:

Tries() int                              // #[Tries] / $tries; 0 retries forever
Backoff() []time.Duration                // #[Backoff] / backoff(); the last value repeats
Timeout() time.Duration                  // #[Timeout] / $timeout
RetryUntil() time.Time                   // retryUntil(); wins over Tries
RetryFor() time.Duration                 // #[RetryFor]: RetryUntil relative to the dispatch
MaxExceptions() int                      // #[MaxExceptions]
FailOnTimeout() bool                     // #[FailOnTimeout] (or embed FailsOnTimeout)
CountCrashesAsExceptions() bool          // #[CountCrashesAsExceptions] (or embed CountsCrashes)
Failed(ctx context.Context, err error)   // failed(): runs once when the job fails for good
Middleware() []Middleware                // middleware()
UniqueID() string                        // with ShouldBeUnique
UniqueFor() time.Duration                // #[UniqueFor]
UniqueVia() Cache                        // uniqueVia()
DebounceFor() time.Duration              // #[DebounceFor]
DebounceMaxWait() time.Duration          // #[DebounceFor(maxWait:)]
DebounceID() string                      // debounceId()
DebounceVia() Cache                      // debounceVia()
PrepareForDispatch(ctx context.Context) bool // PreparesForDispatch; false cancels the dispatch
DeleteWhenMissingModels() bool           // #[DeleteWhenMissingModels] (or embed DeletesMissingModels)
DisplayName() string                     // displayName()
MessageGroup() string                    // SQS FIFO / fair queues
DeduplicationID() string                 // SQS FIFO
JobName() string                         // the registered name; defaults to package.Type

and the marker interfaces ShouldBeUnique, ShouldBeUniqueUntilProcessing, ShouldBeEncrypted, ShouldQueueAfterCommit and ShouldNotQueue, satisfied by embedding Unique, UniqueUntilProcessing, Encrypted, QueueAfterCommit and Sync.

func Call

func Call(name string, args any) Job

Call is a serializable closure job: it runs the function registered under name with args encoded as JSON.

func Closure

func Closure(fn func(ctx context.Context) error) Job

Closure wraps a function as a job (Laravel's dispatch(function () {...})). A Go closure cannot be serialized, so it only runs on the in-process connections (sync, deferred, background) of the Manager that dispatched it. Use RegisterClosure and Call for closures that must cross process boundaries.

type JobAttempted

type JobAttempted struct {
	Connection        string
	Job               *Runtime
	ExceptionOccurred bool
}

JobAttempted fires after every attempt, successful or not.

type JobDebounced

type JobDebounced struct {
	Connection string
	Job        *Runtime
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobExceptionOccurred

type JobExceptionOccurred struct {
	Connection string
	Job        *Runtime
	Err        error
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobFailed

type JobFailed struct {
	Connection string
	Job        *Runtime
	Err        error
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobPopped

type JobPopped struct {
	Connection string
	Job        *Runtime // nil when the queues were empty
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobPopping

type JobPopping struct{ Connection string }

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobProcessed

type JobProcessed struct {
	Connection string
	Job        *Runtime
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobProcessing

type JobProcessing struct {
	Connection string
	Job        *Runtime
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobQueued

type JobQueued struct {
	Connection, Queue string
	ID                string
	Job               Job
	Payload           *Payload
	Delay             time.Duration
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobQueueing

type JobQueueing struct {
	Connection, Queue string
	Job               Job
	Payload           *Payload
	Delay             time.Duration
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobReleasedAfterException

type JobReleasedAfterException struct {
	Connection string
	Job        *Runtime
	Delay      time.Duration
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobRetryRequested

type JobRetryRequested struct{ Failed FailedJob }

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type JobTimedOut

type JobTimedOut struct {
	Connection string
	Job        *Runtime
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type Limit

type Limit struct {
	MaxAttempts int
	Decay       time.Duration
	Key         string
	Unlimited   bool
}

Limit is one rate limit (Laravel's Limit::perMinute(...)->by(...)).

func NoLimit

func NoLimit() Limit

NoLimit is Limit::none().

func PerDay

func PerDay(n int) Limit

func PerHour

func PerHour(n int) Limit

func PerMinute

func PerMinute(n int) Limit

func PerMinutes

func PerMinutes(minutes, n int) Limit

func PerSecond

func PerSecond(n int) Limit

func (Limit) By

func (l Limit) By(key string) Limit

By segments the limit per key (a user id, a tenant, ...).

type Lock

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

Lock is an atomic lock on a Cache (Laravel's Cache::lock).

func NewLock

func NewLock(c Cache, key, owner string, ttl time.Duration) *Lock

NewLock prepares a lock; owner identifies the holder (an empty owner gets a random one).

func (*Lock) ForceRelease

func (l *Lock) ForceRelease(ctx context.Context) error

ForceRelease frees the lock whoever holds it.

func (*Lock) Get

func (l *Lock) Get(ctx context.Context) (bool, error)

Get acquires the lock without waiting.

func (*Lock) Owner

func (l *Lock) Owner() string

Owner is the lock owner token.

func (*Lock) Release

func (l *Lock) Release(ctx context.Context) (bool, error)

Release frees the lock when this owner still holds it.

type Looping

type Looping struct {
	Connection string
	Queues     []string
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type Manager

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

Manager is the queue manager and dispatcher (Laravel's Queue and Bus facades).

func New

func New(cfg Config) (*Manager, error)

New validates cfg and builds a Manager.

func (*Manager) After

func (m *Manager) After(fn func(ctx context.Context, e JobProcessed)) func()

After runs fn after each successful job (Queue::after).

func (*Manager) Batch

func (m *Manager) Batch(items ...any) *PendingBatch

Batch groups jobs whose completion is tracked together (Bus::batch). Items are Job values or []Job chains.

func (*Manager) BatchStore

func (m *Manager) BatchStore() BatchStore

BatchStore is the batch store, nil when batching is not configured.

func (*Manager) Batches

func (m *Manager) Batches(ctx context.Context, limit int, before string) ([]*Batch, error)

Batches lists stored batches newest first (queue:batches).

func (*Manager) Before

func (m *Manager) Before(fn func(ctx context.Context, e JobProcessing)) func()

Before runs fn before each job (Queue::before).

func (*Manager) Bulk

func (m *Manager) Bulk(ctx context.Context, jobs ...Job) error

Bulk pushes many independent jobs, grouped by connection and queue (Bus::bulk). It has none of a batch's tracking or callbacks.

func (*Manager) Cache

func (m *Manager) Cache() Cache

Cache is the cache the manager uses for locks and signals.

func (*Manager) Chain

func (m *Manager) Chain(jobs ...any) *PendingChain

Chain runs jobs one after another; a job that fails stops the rest (Bus::chain). Items are Job values or *PendingBatch (a batch inside the chain).

func (*Manager) Clear

func (m *Manager) Clear(ctx context.Context, connection, queue string) (int64, error)

Clear deletes every job of a queue (queue:clear).

func (*Manager) Close

func (m *Manager) Close() error

Close waits for in-process jobs and closes the drivers that implement Closer. Clients you passed to a driver (Redis, Beanstalkd, SQL) stay yours to close.

func (*Manager) Connection

func (m *Manager) Connection(name string) (Connection, error)

Connection returns the configuration of a named connection ("" is the default).

func (*Manager) Connections

func (m *Manager) Connections() []string

Connections lists the configured connection names, sorted.

func (*Manager) DefaultConnection

func (m *Manager) DefaultConnection() string

DefaultConnection is the name of the default connection.

func (*Manager) Dispatch

func (m *Manager) Dispatch(job Job) *PendingDispatch

Dispatch starts dispatching job (ProcessPodcast::dispatch). Call Send to queue it.

func (*Manager) DispatchAfterResponse

func (m *Manager) DispatchAfterResponse(ctx context.Context, job Job) error

DispatchAfterResponse runs job in this process once the current request is done (dispatchAfterResponse); see DeferredDriver.

func (*Manager) DispatchIf

func (m *Manager) DispatchIf(ctx context.Context, cond bool, job Job) (string, error)

DispatchIf dispatches job only when cond is true.

func (*Manager) DispatchSync

func (m *Manager) DispatchSync(ctx context.Context, job Job) error

DispatchSync runs job now, in this goroutine, and returns its error (dispatchSync).

func (*Manager) DispatchUnless

func (m *Manager) DispatchUnless(ctx context.Context, cond bool, job Job) (string, error)

DispatchUnless dispatches job only when cond is false.

func (*Manager) DontRetry

func (m *Manager) DontRetry(targets ...error)

DontRetry makes jobs that fail with an error matching any target (errors.Is) fail immediately instead of being retried ($exceptions->dontRetry).

func (*Manager) DontRetryWhen

func (m *Manager) DontRetryWhen(fn func(err error) bool)

DontRetryWhen is DontRetry with a predicate ($exceptions->dontRetryWhen).

func (*Manager) FailedJobs

func (m *Manager) FailedJobs() FailedJobStore

FailedJobs is the failed job store.

func (*Manager) Failing

func (m *Manager) Failing(fn func(ctx context.Context, e JobFailed)) func()

Failing runs fn when a job fails (Queue::failing).

func (*Manager) FindBatch

func (m *Manager) FindBatch(ctx context.Context, id string) (*Batch, error)

FindBatch loads a batch (Bus::findBatch).

func (*Manager) Forward

func (m *Manager) Forward(queue, toQueue, connection string)

Forward rewrites dispatches to queue so they go to toQueue, on connection when not empty (Queue::forward). A connection chosen explicitly for the job wins over the forward's.

func (*Manager) Intercept

func (m *Manager) Intercept(i Interceptor) (restore func())

Intercept installs i (nil removes it) and returns the function restoring the previous one.

func (*Manager) IsPaused

func (m *Manager) IsPaused(ctx context.Context, connection, queue string) (bool, error)

IsPaused reports whether connection:queue is paused, on its own or by PauseAll.

func (*Manager) Limiter

func (m *Manager) Limiter(name string) (func(job Job) []Limit, bool)

Limiter returns the named limiter.

func (*Manager) Logger

func (m *Manager) Logger() *slog.Logger

Logger is the manager's logger.

func (*Manager) Looping

func (m *Manager) Looping(fn func(ctx context.Context, e Looping) bool) func()

Looping runs fn before the worker pops a job (Queue::looping); returning false makes the worker skip this iteration.

func (*Manager) Middleware

func (m *Manager) Middleware(next http.Handler) http.Handler

Middleware runs the deferred jobs of each request after its handler returns.

func (*Manager) Monitor

func (m *Manager) Monitor(ctx context.Context, targets []string, max int64) ([]QueueStatus, error)

Monitor reports the size of each target ("connection:queue", or a queue of the default connection) and fires QueueBusy for those holding max jobs or more (queue:monitor).

func (*Manager) Now

func (m *Manager) Now() time.Time

Now is the manager's clock.

func (*Manager) Pause

func (m *Manager) Pause(ctx context.Context, connection, queue string, ttl time.Duration) error

Pause stops workers from taking jobs from connection:queue until Resume, or until ttl passes when ttl > 0 (queue:pause).

func (*Manager) PauseAll

func (m *Manager) PauseAll(ctx context.Context, ttl time.Duration) error

PauseAll pauses every queue of every connection (queue:pause --all).

func (*Manager) RateLimiter

func (m *Manager) RateLimiter(name string, fn func(job Job) []Limit)

RateLimiter defines a named limiter for middleware.RateLimited (RateLimiter::for).

func (*Manager) Restart

func (m *Manager) Restart(ctx context.Context) error

Restart tells every worker to exit after its current job (queue:restart).

func (*Manager) Resume

func (m *Manager) Resume(ctx context.Context, connection, queue string) error

Resume lets workers take jobs from connection:queue again (queue:resume / queue:continue).

func (*Manager) ResumeAll

func (m *Manager) ResumeAll(ctx context.Context) error

ResumeAll lifts PauseAll; queues paused one by one stay paused (queue:resume --all).

func (*Manager) RetryBatch

func (m *Manager) RetryBatch(ctx context.Context, id string) error

RetryBatch retries the failed jobs of a batch (queue:retry-batch).

func (*Manager) RetryFailed

func (m *Manager) RetryFailed(ctx context.Context, ids ...string) error

RetryFailed pushes failed jobs back onto their original connection and queue with fresh attempts, then forgets them (queue:retry).

func (*Manager) RetryFailedQueue

func (m *Manager) RetryFailedQueue(ctx context.Context, queue string) error

RetryFailedQueue retries every failed job of queue (queue:retry --queue).

func (*Manager) Route

func (m *Manager) Route(prototype Job, connection, queue string)

Route sends every job of prototype's type to connection and queue unless the dispatch says otherwise (Queue::route). An empty connection or queue keeps the default.

func (*Manager) RouteMatching

func (m *Manager) RouteMatching(match func(Job) bool, connection, queue string)

RouteMatching routes every job for which match returns true; use it to route by interface, embedded type or anything else (Queue::route with an interface, trait or parent class).

func (*Manager) Size

func (m *Manager) Size(ctx context.Context, connection, queue string) (int64, error)

Size counts the jobs of a queue ("" is the connection's default queue).

func (*Manager) Transaction

func (m *Manager) Transaction(ctx context.Context, fn func(ctx context.Context) error) error

Transaction runs fn in an after-commit scope: when fn returns nil the buffered jobs are dispatched, otherwise they are dropped. Run your database transaction inside fn with the context it receives (database.Transaction does both for a migro database).

func (*Manager) Wait

func (m *Manager) Wait()

Wait blocks until every background and deferred job started by this manager returns.

func (*Manager) WithoutInterruptionPolling

func (m *Manager) WithoutInterruptionPolling()

WithoutInterruptionPolling makes workers skip the cache checks for queue:restart and queue:pause (Queue::withoutInterruptionPolling).

func (*Manager) Work

func (m *Manager) Work(ctx context.Context, o WorkerOptions) (int, error)

Work runs a worker until a stop condition (queue:work). It returns the exit status.

type MemoryBatchStore

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

MemoryBatchStore keeps batches in memory (tests, single-process apps).

func NewMemoryBatchStore

func NewMemoryBatchStore() *MemoryBatchStore

NewMemoryBatchStore returns an empty in-memory batch store.

func (*MemoryBatchStore) Cancel

func (s *MemoryBatchStore) Cancel(_ context.Context, id string, at time.Time) error

func (*MemoryBatchStore) Delete

func (s *MemoryBatchStore) Delete(_ context.Context, id string) error

func (*MemoryBatchStore) Find

func (s *MemoryBatchStore) Find(_ context.Context, id string) (*Batch, error)

func (*MemoryBatchStore) IncrementTotalJobs

func (s *MemoryBatchStore) IncrementTotalJobs(_ context.Context, id string, n int) error

func (*MemoryBatchStore) List

func (s *MemoryBatchStore) List(_ context.Context, limit int, before string) ([]*Batch, error)

func (*MemoryBatchStore) MarkFinished

func (s *MemoryBatchStore) MarkFinished(_ context.Context, id string, at time.Time) error

func (*MemoryBatchStore) Prune

func (s *MemoryBatchStore) Prune(_ context.Context, before time.Time) (int64, error)

func (*MemoryBatchStore) PruneCancelled

func (s *MemoryBatchStore) PruneCancelled(_ context.Context, before time.Time) (int64, error)

func (*MemoryBatchStore) PruneUnfinished

func (s *MemoryBatchStore) PruneUnfinished(_ context.Context, before time.Time) (int64, error)

func (*MemoryBatchStore) RecordFailure

func (s *MemoryBatchStore) RecordFailure(_ context.Context, id, jobID string) (*Batch, error)

func (*MemoryBatchStore) RecordSuccess

func (s *MemoryBatchStore) RecordSuccess(_ context.Context, id, jobID string) (*Batch, error)

func (*MemoryBatchStore) Store

func (s *MemoryBatchStore) Store(_ context.Context, b *Batch) error

type MemoryCache

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

MemoryCache is a Cache for a single process (tests, sync/background connections).

func NewMemoryCache

func NewMemoryCache() *MemoryCache

NewMemoryCache returns an empty in-process cache.

func (*MemoryCache) Add

func (c *MemoryCache) Add(_ context.Context, key, value string, ttl time.Duration) (bool, error)

func (*MemoryCache) Forget

func (c *MemoryCache) Forget(_ context.Context, key string) error

func (*MemoryCache) ForgetIf

func (c *MemoryCache) ForgetIf(_ context.Context, key, value string) (bool, error)

func (*MemoryCache) Get

func (c *MemoryCache) Get(_ context.Context, key string) (string, bool, error)

func (*MemoryCache) Increment

func (c *MemoryCache) Increment(_ context.Context, key string, by int64, ttl time.Duration) (int64, error)

func (*MemoryCache) Put

func (c *MemoryCache) Put(_ context.Context, key, value string, ttl time.Duration) error

func (*MemoryCache) SetClock

func (c *MemoryCache) SetClock(now func() time.Time)

SetClock replaces the cache's clock (tests).

type MemoryDriver

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

MemoryDriver is a complete queue kept in this process: delays, reservations and retry_after behave like the database driver. Useful for tests and single-process apps.

func NewMemoryDriver

func NewMemoryDriver(retryAfter time.Duration) *MemoryDriver

NewMemoryDriver returns an empty memory queue; reserved jobs come back after retryAfter (90s when 0).

func (*MemoryDriver) Clear

func (d *MemoryDriver) Clear(_ context.Context, queue string) (int64, error)

func (*MemoryDriver) DelayedSize

func (d *MemoryDriver) DelayedSize(_ context.Context, queue string) (int64, error)

func (*MemoryDriver) InProcess

func (d *MemoryDriver) InProcess() bool

InProcess reports true: jobs never leave the process, so closures are allowed.

func (*MemoryDriver) OldestPending

func (d *MemoryDriver) OldestPending(_ context.Context, queue string) (time.Time, error)

func (*MemoryDriver) Payloads

func (d *MemoryDriver) Payloads(queue string) [][]byte

Payloads returns the payloads of a queue in order (tests).

func (*MemoryDriver) PendingSize

func (d *MemoryDriver) PendingSize(_ context.Context, queue string) (int64, error)

func (*MemoryDriver) Pop

func (d *MemoryDriver) Pop(_ context.Context, queue string) (Reserved, error)

func (*MemoryDriver) Push

func (d *MemoryDriver) Push(_ context.Context, m Message) (string, error)

func (*MemoryDriver) PushBulk

func (d *MemoryDriver) PushBulk(ctx context.Context, ms []Message) ([]string, error)

func (*MemoryDriver) ReservedSize

func (d *MemoryDriver) ReservedSize(_ context.Context, queue string) (int64, error)

func (*MemoryDriver) SetClock

func (d *MemoryDriver) SetClock(now func() time.Time)

SetClock replaces the driver's clock (tests).

func (*MemoryDriver) Size

func (d *MemoryDriver) Size(_ context.Context, queue string) (int64, error)

type MemoryFailedJobStore

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

MemoryFailedJobStore keeps failed jobs in memory.

func NewMemoryFailedJobStore

func NewMemoryFailedJobStore() *MemoryFailedJobStore

NewMemoryFailedJobStore returns an empty in-memory failed job store.

func (*MemoryFailedJobStore) All

func (*MemoryFailedJobStore) Find

func (*MemoryFailedJobStore) Flush

func (s *MemoryFailedJobStore) Flush(_ context.Context, olderThan time.Duration) (int64, error)

func (*MemoryFailedJobStore) Forget

func (s *MemoryFailedJobStore) Forget(_ context.Context, id string) (bool, error)

func (*MemoryFailedJobStore) IDs

func (s *MemoryFailedJobStore) IDs(_ context.Context, queue string) ([]string, error)

func (*MemoryFailedJobStore) Log

func (*MemoryFailedJobStore) Prune

func (s *MemoryFailedJobStore) Prune(_ context.Context, before time.Time) (int64, error)

type Message

type Message struct {
	ID              string // the payload UUID; drivers may use it as their job id
	Queue           string
	Payload         []byte
	Delay           time.Duration
	Group           string // SQS message group (FIFO and fair queues)
	DeduplicationID string // SQS FIFO deduplication id
}

Message is one job handed to a driver.

type Middleware

type Middleware interface {
	Handle(ctx context.Context, job Job, next Next) error
}

Middleware wraps a job's Handle (job middleware). Use JobFrom(ctx) to release or delete the job.

type MiddlewareFunc

type MiddlewareFunc func(ctx context.Context, job Job, next Next) error

MiddlewareFunc adapts a function to Middleware.

func (MiddlewareFunc) Handle

func (f MiddlewareFunc) Handle(ctx context.Context, job Job, next Next) error

type Next

type Next func(ctx context.Context) error

Next calls the rest of the middleware pipeline and, at its end, the job.

type NullFailedJobStore

type NullFailedJobStore struct{}

NullFailedJobStore stores nothing (failed job storage disabled).

func (NullFailedJobStore) All

func (NullFailedJobStore) Find

func (NullFailedJobStore) Flush

func (NullFailedJobStore) Forget

func (NullFailedJobStore) IDs

func (NullFailedJobStore) Log

func (NullFailedJobStore) Prune

type Payload

type Payload struct {
	UUID        string          `json:"uuid"`
	DisplayName string          `json:"displayName"`
	Job         string          `json:"job"`
	Data        json.RawMessage `json:"data,omitempty"`
	Secret      string          `json:"secret,omitempty"`

	// Settings resolved at dispatch. MaxTries nil means "use the worker's --tries".
	MaxTries      *int    `json:"maxTries,omitempty"`
	MaxExceptions int     `json:"maxExceptions,omitempty"`
	Backoff       []int64 `json:"backoff,omitempty"` // milliseconds
	Timeout       int64   `json:"timeout,omitempty"` // milliseconds; 0 uses the worker's --timeout
	RetryUntil    int64   `json:"retryUntil,omitempty"`
	FailOnTimeout bool    `json:"failOnTimeout,omitempty"`
	CountCrashes  bool    `json:"countCrashes,omitempty"`
	DeleteMissing bool    `json:"deleteWhenMissingModels,omitempty"`

	Connection string `json:"connection"`
	Queue      string `json:"queue"`
	Group      string `json:"group,omitempty"`
	DedupID    string `json:"deduplicationId,omitempty"`

	// Chain holds the payloads of the jobs that run after this one; ChainCatch the callbacks
	// that run when any of them fails.
	Chain           []json.RawMessage `json:"chain,omitempty"`
	ChainConnection string            `json:"chainConnection,omitempty"`
	ChainQueue      string            `json:"chainQueue,omitempty"`
	ChainCatch      []json.RawMessage `json:"chainCatch,omitempty"`

	BatchID string `json:"batchId,omitempty"`
	// Delay is the delay of a chained job, applied when the chain reaches it (milliseconds).
	Delay int64 `json:"delay,omitempty"`

	UniqueKey             string `json:"uniqueKey,omitempty"`
	UniqueUntilProcessing bool   `json:"uniqueUntilProcessing,omitempty"`
	DebounceKey           string `json:"debounceKey,omitempty"`

	CreatedAt int64 `json:"createdAt"`
}

Payload is the envelope a driver stores. Data is the job's JSON; when the job is ShouldBeEncrypted, Data is empty and Secret holds it sealed with AES-256-GCM.

func DecodePayload

func DecodePayload(raw []byte) (*Payload, error)

DecodePayload parses a stored payload.

type PendingBatch

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

PendingBatch is a batch being configured (Bus::batch).

func (*PendingBatch) AllowFailures

func (p *PendingBatch) AllowFailures(allow ...bool) *PendingBatch

func (*PendingBatch) AllowsFailures

func (p *PendingBatch) AllowsFailures() bool

AllowsFailures reports whether failures leave the batch running.

func (*PendingBatch) BatchName

func (p *PendingBatch) BatchName() string

BatchName is the batch name.

func (*PendingBatch) Before

func (p *PendingBatch) Before(fn func(ctx context.Context, b *Batch)) *PendingBatch

Before runs fn in this process once the batch is stored, before its jobs are queued.

func (*PendingBatch) Catch

func (p *PendingBatch) Catch(fn func(ctx context.Context, b *Batch, err error)) *PendingBatch

Catch runs fn on the first job failure.

func (*PendingBatch) CatchJob

func (p *PendingBatch) CatchJob(job Job) *PendingBatch

func (*PendingBatch) Dispatch

func (p *PendingBatch) Dispatch(ctx context.Context) (*Batch, error)

Dispatch stores the batch and queues its jobs.

func (*PendingBatch) DispatchIf

func (p *PendingBatch) DispatchIf(ctx context.Context, cond bool) (*Batch, error)

DispatchIf dispatches the batch only when cond is true.

func (*PendingBatch) Finally

func (p *PendingBatch) Finally(fn func(ctx context.Context, b *Batch)) *PendingBatch

Finally runs fn once every job has run, whatever the outcome.

func (*PendingBatch) FinallyJob

func (p *PendingBatch) FinallyJob(job Job) *PendingBatch

func (*PendingBatch) Jobs

func (p *PendingBatch) Jobs() []any

Jobs is the batch's items.

func (*PendingBatch) Name

func (p *PendingBatch) Name(name string) *PendingBatch

func (*PendingBatch) OnConnection

func (p *PendingBatch) OnConnection(name string) *PendingBatch

func (*PendingBatch) OnQueue

func (p *PendingBatch) OnQueue(name string) *PendingBatch

func (*PendingBatch) Progress

func (p *PendingBatch) Progress(fn func(ctx context.Context, b *Batch)) *PendingBatch

Progress runs fn after each job completes.

func (*PendingBatch) ProgressJob

func (p *PendingBatch) ProgressJob(job Job) *PendingBatch

func (*PendingBatch) Target

func (p *PendingBatch) Target() (connection, queue string)

Target is the connection and queue the batch dispatches to.

func (*PendingBatch) Then

func (p *PendingBatch) Then(fn func(ctx context.Context, b *Batch)) *PendingBatch

Then runs fn when every job succeeded. Closures only run in this process: see ThenJob.

func (*PendingBatch) ThenJob

func (p *PendingBatch) ThenJob(job Job) *PendingBatch

ThenJob, CatchJob, FinallyJob and ProgressJob register serializable callbacks: the job runs inline in the worker that completes the batch, with BatchFrom(ctx) and ErrorFrom(ctx).

type PendingChain

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

PendingChain is a chain being configured (Bus::chain).

func (*PendingChain) Catch

func (c *PendingChain) Catch(fn func(ctx context.Context, err error)) *PendingChain

Catch runs fn when a job of the chain fails. fn is a Go closure, so it only runs in this process; use CatchJob on connections served by other processes.

func (*PendingChain) CatchJob

func (c *PendingChain) CatchJob(job Job) *PendingChain

CatchJob runs job inline when a job of the chain fails; ErrorFrom(ctx) is the failure.

func (*PendingChain) Delay

func (c *PendingChain) Delay(d time.Duration) *PendingChain

Delay delays the first job.

func (*PendingChain) Dispatch

func (c *PendingChain) Dispatch(ctx context.Context) (string, error)

Dispatch queues the first job; the others travel in its payload.

func (*PendingChain) Jobs

func (c *PendingChain) Jobs() []any

Jobs is the chain's items.

func (*PendingChain) OnConnection

func (c *PendingChain) OnConnection(name string) *PendingChain

OnConnection sets the connection of every job of the chain that does not choose one.

func (*PendingChain) OnQueue

func (c *PendingChain) OnQueue(name string) *PendingChain

OnQueue sets the queue of every job of the chain that does not choose one.

type PendingDispatch

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

PendingDispatch is a dispatch being configured; nothing is queued until Send.

func (*PendingDispatch) AfterCommit

func (p *PendingDispatch) AfterCommit() *PendingDispatch

AfterCommit holds the job until the surrounding Manager.Transaction commits.

func (*PendingDispatch) BeforeCommit

func (p *PendingDispatch) BeforeCommit() *PendingDispatch

BeforeCommit dispatches right away even on an after_commit connection.

func (*PendingDispatch) Catch

func (p *PendingDispatch) Catch(fn func(ctx context.Context, err error)) *PendingDispatch

Catch runs fn when the job fails for good (dispatch(fn)->catch(...)). fn is a Go closure, so it runs only when the failing worker is this process; use CatchJob otherwise.

func (*PendingDispatch) CatchJob

func (p *PendingDispatch) CatchJob(job Job) *PendingDispatch

CatchJob runs job inline when the job fails for good; ErrorFrom(ctx) is the failure.

func (*PendingDispatch) Chain

func (p *PendingDispatch) Chain(jobs ...any) *PendingDispatch

Chain runs jobs (Job values or *PendingBatch) one after another once this job succeeds (withChain).

func (*PendingDispatch) Delay

Delay makes the job available after d.

func (*PendingDispatch) DelayUntil

func (p *PendingDispatch) DelayUntil(t time.Time) *PendingDispatch

DelayUntil makes the job available at t.

func (*PendingDispatch) If

func (p *PendingDispatch) If(cond bool) *PendingDispatch

If skips the dispatch when cond is false.

func (*PendingDispatch) OnConnection

func (p *PendingDispatch) OnConnection(name string) *PendingDispatch

func (*PendingDispatch) OnGroup

func (p *PendingDispatch) OnGroup(group string) *PendingDispatch

OnGroup sets the SQS message group (FIFO ordering, fair queues).

func (*PendingDispatch) OnQueue

func (p *PendingDispatch) OnQueue(name string) *PendingDispatch

func (*PendingDispatch) Send

func (p *PendingDispatch) Send(ctx context.Context) (string, error)

Send queues the job and returns its UUID. An empty id with a nil error means the dispatch was skipped on purpose: a false condition, PrepareForDispatch returning false, or a unique job whose lock is held.

func (*PendingDispatch) WithDeduplicationID

func (p *PendingDispatch) WithDeduplicationID(id string) *PendingDispatch

WithDeduplicationID sets the SQS FIFO deduplication id.

func (*PendingDispatch) WithoutDelay

func (p *PendingDispatch) WithoutDelay() *PendingDispatch

WithoutDelay ignores the job's default delay.

type QueueAfterCommit

type QueueAfterCommit struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (QueueAfterCommit) ShouldQueueAfterCommit

func (QueueAfterCommit) ShouldQueueAfterCommit()

type QueueBusy

type QueueBusy struct {
	Connection, Queue string
	Size              int64
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type QueueFailedOver

type QueueFailedOver struct {
	Connection string // the connection that failed
	Err        error
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type QueuePaused

type QueuePaused struct {
	Connection, Queue string
	TTL               time.Duration
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type QueueResumed

type QueueResumed struct{ Connection, Queue string }

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type QueueStatus

type QueueStatus struct {
	Connection    string
	Queue         string
	Size          int64
	Pending       int64
	Delayed       int64
	Reserved      int64
	OldestPending time.Time
	Busy          bool
}

QueueStatus is one row of queue:monitor. The breakdown is -1 when the driver cannot report it.

type Queueable

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

Queueable gives a job Laravel's Queueable, InteractsWithQueue and Batchable methods. Embed it in the job struct; it is never serialized.

type ProcessPodcast struct {
	perago.Queueable
	PodcastID int
}

The OnQueue/OnConnection/... setters are defaults the dispatch may override. The other methods work while the job is being handled.

func (*Queueable) AfterCommit

func (q *Queueable) AfterCommit()

AfterCommit makes the job wait for the surrounding Manager.Transaction to commit.

func (*Queueable) AppendToChain

func (q *Queueable) AppendToChain(job Job) error

AppendToChain runs job at the end of this job's chain.

func (*Queueable) Attempts

func (q *Queueable) Attempts() int

Attempts is how many times the job has been attempted, this attempt included.

func (*Queueable) Batch

func (q *Queueable) Batch(ctx context.Context) (*Batch, error)

Batch loads the job's batch, nil when it is not batched.

func (*Queueable) BatchID

func (q *Queueable) BatchID() string

BatchID is the id of the job's batch, "" when it is not batched.

func (*Queueable) BeforeCommit

func (q *Queueable) BeforeCommit()

BeforeCommit dispatches the job right away even on an after_commit connection.

func (*Queueable) DelayFor

func (q *Queueable) DelayFor(d time.Duration)

DelayFor sets the job's default delay.

func (*Queueable) Delete

func (q *Queueable) Delete()

Delete removes the job from the queue; a chain still continues.

func (*Queueable) Fail

func (q *Queueable) Fail(reason ...any)

Fail marks the job as failed. reason is an error, a string, or nothing.

func (*Queueable) Job

func (q *Queueable) Job() *Runtime

Job is the job's runtime while it runs, nil otherwise.

func (*Queueable) JobID

func (q *Queueable) JobID() string

JobID is the job's UUID.

func (*Queueable) OnConnection

func (q *Queueable) OnConnection(name string)

OnConnection sets the job's default connection.

func (*Queueable) OnGroup

func (q *Queueable) OnGroup(group string)

OnGroup sets the SQS message group.

func (*Queueable) OnQueue

func (q *Queueable) OnQueue(name string)

OnQueue sets the job's default queue.

func (*Queueable) PrependToChain

func (q *Queueable) PrependToChain(job Job) error

PrependToChain runs job right after this one.

func (*Queueable) Release

func (q *Queueable) Release(delay ...time.Duration)

Release puts the job back on the queue, available after delay (0 when omitted).

func (*Queueable) ReleaseUsingBackoff

func (q *Queueable) ReleaseUsingBackoff()

ReleaseUsingBackoff releases the job with the delay its backoff sets for this attempt.

type Reserved

type Reserved interface {
	ID() string
	Queue() string
	Payload() []byte
	Attempts() int
	Delete(ctx context.Context) error
	Release(ctx context.Context, delay time.Duration) error
}

Reserved is a job a worker popped. Attempts counts reservations, this one included.

type Restorable

type Restorable interface {
	Restore(ctx context.Context) error
}

Restorable is implemented by payload fields that must be reloaded before the job runs, such as model.Of[T]: only the key travels, the record is fetched again in the worker. Returning an error matching ErrModelNotFound deletes the job when it DeleteWhenMissingModels.

type Runtime

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

Runtime is a job being processed (Laravel's Illuminate\Contracts\Queue\Job). Jobs reach it through the embedded Queueable or JobFrom(ctx); middleware through JobFrom.

func JobFrom

func JobFrom(ctx context.Context) (*Runtime, bool)

JobFrom returns the job runtime of a context passed to Handle or to a middleware.

func NewFakeRuntime

func NewFakeRuntime(job Job, attempts int) *Runtime

NewFakeRuntime binds job to a runtime that only records what the job does with the queue (release, delete, fail, chain changes). queuetest.WithFakeQueueInteractions uses it.

func (*Runtime) AppendToChain

func (r *Runtime) AppendToChain(job Job) error

AppendToChain runs job at the end of this job's chain.

func (*Runtime) Attempts

func (r *Runtime) Attempts() int

Attempts is how many times the job has been attempted, this attempt included.

func (*Runtime) Batch

func (r *Runtime) Batch(ctx context.Context) (*Batch, error)

Batch loads the job's batch, nil when it is not batched.

func (*Runtime) Chain

func (r *Runtime) Chain() []*Payload

Chain is the payloads still to run after this job.

func (*Runtime) Connection

func (r *Runtime) Connection() string

Connection is the connection the job was popped from.

func (*Runtime) Delete

func (r *Runtime) Delete()

Delete removes the job from the queue.

func (*Runtime) DisplayName

func (r *Runtime) DisplayName() string

DisplayName is the job's display name.

func (*Runtime) Fail

func (r *Runtime) Fail(err error)

Fail marks the job as failed with err.

func (*Runtime) HasFailed

func (r *Runtime) HasFailed() (bool, error)

HasFailed reports whether the job was marked as failed, and why.

func (*Runtime) ID

func (r *Runtime) ID() string

ID is the driver's id for the job.

func (*Runtime) IsDeleted

func (r *Runtime) IsDeleted() bool

IsDeleted reports whether the job deleted itself.

func (*Runtime) IsReleased

func (r *Runtime) IsReleased() (bool, time.Duration)

IsReleased reports whether the job was released, and with what delay.

func (*Runtime) Job

func (r *Runtime) Job() Job

Job is the decoded job (nil when it could not be decoded).

func (*Runtime) Manager

func (r *Runtime) Manager() *Manager

Manager is the manager processing the job.

func (*Runtime) MaxTries

func (r *Runtime) MaxTries(fallback int) int

MaxTries is the job's resolved tries (0 = unlimited).

func (*Runtime) Name

func (r *Runtime) Name() string

Name is the registered job name.

func (*Runtime) Payload

func (r *Runtime) Payload() *Payload

Payload is the job's envelope.

func (*Runtime) PrependToChain

func (r *Runtime) PrependToChain(job Job) error

PrependToChain runs job right after this one.

func (*Runtime) Queue

func (r *Runtime) Queue() string

Queue is the queue the job was popped from.

func (*Runtime) Release

func (r *Runtime) Release(delay time.Duration)

Release puts the job back on the queue after delay.

func (*Runtime) ReleaseUsingBackoff

func (r *Runtime) ReleaseUsingBackoff()

ReleaseUsingBackoff releases the job with the delay of its backoff for this attempt.

func (*Runtime) SetFakeBatch

func (r *Runtime) SetFakeBatch(b *Batch)

SetFakeBatch makes Batch return b (queuetest.WithFakeBatch).

func (*Runtime) UUID

func (r *Runtime) UUID() string

UUID is the job's UUID.

type ShouldBeEncrypted

type ShouldBeEncrypted interface{ ShouldBeEncrypted() }

Marker interfaces (Laravel's ShouldBeUnique, ShouldBeEncrypted, ...).

type ShouldBeUnique

type ShouldBeUnique interface{ ShouldBeUnique() }

Marker interfaces (Laravel's ShouldBeUnique, ShouldBeEncrypted, ...).

type ShouldBeUniqueUntilProcessing

type ShouldBeUniqueUntilProcessing interface{ ShouldBeUniqueUntilProcessing() }

Marker interfaces (Laravel's ShouldBeUnique, ShouldBeEncrypted, ...).

type ShouldNotQueue

type ShouldNotQueue interface{ ShouldNotQueue() }

ShouldNotQueue jobs run in the dispatching process (a job made with make:job --sync).

type ShouldQueueAfterCommit

type ShouldQueueAfterCommit interface{ ShouldQueueAfterCommit() }

Marker interfaces (Laravel's ShouldBeUnique, ShouldBeEncrypted, ...).

type SizeReporter

type SizeReporter interface {
	PendingSize(ctx context.Context, queue string) (int64, error)
	DelayedSize(ctx context.Context, queue string) (int64, error)
	ReservedSize(ctx context.Context, queue string) (int64, error)
}

SizeReporter breaks Size down (Queue::pendingSize, delayedSize, reservedSize).

type Sync

type Sync struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (Sync) ShouldNotQueue

func (Sync) ShouldNotQueue()

type Tx

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

Tx buffers the dispatches of an after-commit scope.

func BeginTransaction

func BeginTransaction(ctx context.Context) (context.Context, *Tx)

BeginTransaction opens an after-commit scope. Dispatches made with the returned context to an AfterCommit connection (or with AfterCommit()) wait for Commit; Rollback drops them. Scopes nest: an inner Commit hands its jobs to the outer scope.

func (*Tx) Commit

func (t *Tx) Commit(ctx context.Context) error

Commit dispatches the buffered jobs, or passes them to the enclosing scope.

func (*Tx) Rollback

func (t *Tx) Rollback()

Rollback drops the buffered jobs.

type Unique

type Unique struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (Unique) ShouldBeUnique

func (Unique) ShouldBeUnique()

type UniqueUntilProcessing

type UniqueUntilProcessing struct{}

Embeddable markers. They have no fields, so they never show up in the payload.

func (UniqueUntilProcessing) ShouldBeUnique

func (UniqueUntilProcessing) ShouldBeUnique()

func (UniqueUntilProcessing) ShouldBeUniqueUntilProcessing

func (UniqueUntilProcessing) ShouldBeUniqueUntilProcessing()

type WorkerIdle

type WorkerIdle struct {
	Connection string
	Queues     []string
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type WorkerOptions

type WorkerOptions struct {
	// Name identifies the worker (--name), shown in logs.
	Name string
	// Connection to work ("" is the default connection).
	Connection string
	// Queues in priority order (--queue=high,default); empty uses the connection's default queue.
	Queues []string
	// Backoff applies to jobs that declare none (--backoff=10,30); the last value repeats.
	Backoff []time.Duration
	// Tries applies to jobs that declare none (--tries). 0 means the default, 1; a negative
	// value retries forever (--tries=0).
	Tries int
	// Timeout per job (--timeout, default 60s); negative disables it.
	Timeout time.Duration
	// Grace is how long a timed-out job gets to return after its context is cancelled; when it
	// does not, the worker stops with ExitError so a supervisor can replace the process.
	// Default 5s.
	Grace time.Duration
	// Sleep between polls when every queue is empty (--sleep, default 3s).
	Sleep time.Duration
	// Rest after each job (--rest).
	Rest time.Duration
	// MemoryMB stops the worker (ExitMemoryLimit) once the process uses more (--memory=128).
	MemoryMB int
	// MemoryPercent stops it past this share of the machine's or container's memory (--memory=60%).
	MemoryPercent float64
	// MaxJobs stops the worker after processing this many jobs (--max-jobs).
	MaxJobs int
	// MaxTime stops the worker once it has run this long (--max-time).
	MaxTime time.Duration
	// Once processes a single job, or none, and returns (--once).
	Once bool
	// StopWhenEmpty returns once every queue is empty (--stop-when-empty).
	StopWhenEmpty bool
	// Force processes jobs even while Maintenance reports true (--force).
	Force bool
	// Maintenance reports whether the application is in maintenance mode.
	Maintenance func() bool
	// SkipRestartPolling and SkipPausePolling stop the worker from checking the cache for
	// queue:restart and queue:pause before each job (Worker::$restartable / $pausable = false).
	SkipRestartPolling bool
	SkipPausePolling   bool
	// HandleSignals installs SIGTERM/SIGINT/SIGQUIT (finish the job, then exit),
	// SIGUSR2 (pause) and SIGCONT (continue) handlers.
	HandleSignals bool
}

WorkerOptions are queue:work's flags.

type WorkerStarting

type WorkerStarting struct {
	Connection string
	Queues     []string
	Options    WorkerOptions
}

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

type WorkerStopping

type WorkerStopping struct{ Status int }

Queue events (Illuminate\Queue\Events\*). Listen with perago.Listen[E](m, fn) or the Before/After/Failing/Looping shortcuts.

Directories

Path Synopsis
beanstalkd module
cmd
perago command
Command perago runs the make:* generators anywhere and forwards every other command to your application's console (a main package that runs console.App), found at ./cmd/perago or at the path in PERAGO_APP, through `go run`.
Command perago runs the make:* generators anywhere and forwards every other command to your application's console (a main package that runs console.App), found at ./cmd/perago or at the path in PERAGO_APP, through `go run`.
Package console is the artisan-style command line for perago: queue:work, queue:listen, queue:retry, queue:failed, queue:monitor, make:job and the rest.
Package console is the artisan-style command line for perago: queue:work, queue:listen, queue:retry, queue:failed, queue:monitor, make:job and the rest.
Package database stores perago's queue, failed jobs, batches and cache in a SQL database.
Package database stores perago's queue, failed jobs, batches and cache in a SQL database.
dynamodb module
internal
cachetest
Package cachetest is the conformance suite every perago.Cache passes.
Package cachetest is the conformance suite every perago.Cache passes.
drivertest
Package drivertest is the conformance suite every perago queue driver passes.
Package drivertest is the conformance suite every perago queue driver passes.
e2etest
Package e2etest is perago's end-to-end suite: Laravel's queue scenarios run through the Manager and a real worker on top of one backend (a driver, a cache, a failed job store and a batch store).
Package e2etest is perago's end-to-end suite: Laravel's queue scenarios run through the Manager and a real worker on top of one backend (a driver, a cache, a failed job store and a batch store).
Package middleware has Laravel's job middleware: RateLimited, WithoutOverlapping, ThrottlesExceptions, Release, Skip and SkipIfBatchCancelled.
Package middleware has Laravel's job middleware: RateLimited, WithoutOverlapping, ThrottlesExceptions, Release, Skip and SkipIfBatchCancelled.
migro module
Package queuetest is Laravel's Queue::fake and Bus::fake for perago: capture dispatches instead of queueing them, then assert on what was pushed, chained and batched; or run a job with a fake runtime and assert what it did to the queue (released, deleted, failed).
Package queuetest is Laravel's Queue::fake and Bus::fake for perago: capture dispatches instead of queueing them, then assert on what was pushed, chained and batched; or run a job with a fake runtime and assert what it did to the queue (released, deleted, failed).
redis module
sqs module

Jump to

Keyboard shortcuts

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