sqs

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 15 Imported by: 0 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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrVisibilityLost is the cause of a handler's context cancellation when the worker could not keep one of
	// the batch's messages hidden. Another worker may already have received that message, so the handler
	// should stop work on it without writing anything; Mark is a no-op for it. The context of the whole batch
	// is cancelled, but the batch's other messages are still held, and the handler may still mark the ones it
	// finished. This also happens to a job still running 12 hours after its message was received, the most
	// SQS keeps a message hidden.
	ErrVisibilityLost = errors.New("sqs worker: message visibility lost")
)

Functions

This section is empty.

Types

type FailedMessage added in v0.15.0

type FailedMessage struct {
	// Index is the body's position in the slice passed to SendBatch.
	Index       int
	Code        string
	Message     string
	SenderFault bool
}

FailedMessage is one body SQS rejected.

type HandlerFunc

type HandlerFunc func(ctx context.Context, batch []Message)

HandlerFunc is invoked for each batch of up to BatchSize messages.

The handler decides whether each message is done: Mark deletes it, and a message not marked is redelivered once its visibility timeout ends. Mark before returning; once the handler returns, Mark does nothing.

type Message

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

Message wraps an SQS message. The handler calls Mark when it is done with the message; a message not marked is redelivered once its visibility timeout ends.

func (Message) Mark

func (m Message) Mark()

Mark best-effort enqueues this message for background deletion. It is a no-op if required fields are missing, once the message has been dropped, or after the handler has returned.

func (Message) Raw

func (m Message) Raw() types.Message

Raw returns the underlying AWS SDK message. This keeps the wrapper non-leaky while still allowing full access when needed.

type Option

type Option func(*Options) error

Option mutates Options (variadic functional options style).

func WithBatchSize

func WithBatchSize(n int) Option

func WithDeleteBatchSize

func WithDeleteBatchSize(n int) Option

func WithDeleteBatchWindow

func WithDeleteBatchWindow(d time.Duration) Option

func WithHeartbeat added in v0.16.0

func WithHeartbeat(interval, extension time.Duration) Option

WithHeartbeat sets how long each receive and extension hides a message, and how often the worker extends the messages it holds. The defaults are 3 and 6 minutes. extension must be whole seconds, and SQS stops extending a message 12 hours after it was received.

func WithLogger

func WithLogger(l *slog.Logger) Option

func WithMaxPrefetched added in v0.16.0

func WithMaxPrefetched(n int) Option

WithMaxPrefetched sets the most received messages that may wait in memory for a busy handler. The default is 10. Use 0 for long jobs, so the worker receives only for idle handlers.

func WithQueueURL

func WithQueueURL(url string) Option

func WithSQSClient

func WithSQSClient(c sqsClient) Option

func WithWaitTimeSeconds

func WithWaitTimeSeconds(n int32) Option

func WithWorkerCount

func WithWorkerCount(n int) Option

type Options

type Options struct {
	// Required
	QueueURL string

	// Optional. If nil, New() should create a client using gommon/pkg/aws GetConfig().
	Client sqsClient

	// Optional. If nil, the worker should use slog.Default().
	Logger *slog.Logger

	// Concurrency
	WorkerCount int

	// Batching
	// BatchSize is the most messages passed to your handler at once (1..10). A free handler takes up to
	// BatchSize of the oldest waiting messages and does not wait for a full batch.
	BatchSize int

	// ReceiveMessage tuning
	// WaitTimeSeconds controls SQS long-polling (0..20).
	WaitTimeSeconds int32

	// Delete batching
	// DeleteBatchSize controls max entries per DeleteMessageBatch call (1..10).
	DeleteBatchSize int
	// DeleteBatchWindow controls periodic flushing even if the delete batch isn't full.
	DeleteBatchWindow time.Duration

	// MaxPrefetched is the most received messages that may wait in memory for a busy handler. The worker
	// receives only as many messages as it can hold: a full batch for every idle handler plus up to
	// MaxPrefetched waiting. The default is 10. Use 0 for long jobs, so the worker receives only for idle
	// handlers and waiting messages stay in the queue for other workers.
	MaxPrefetched int

	// HeartbeatInterval and HeartbeatExtension control how the worker keeps the messages it holds hidden.
	// Each receive hides messages for HeartbeatExtension, and every HeartbeatInterval the worker resets
	// every held message, waiting or running, to stay hidden for HeartbeatExtension from then. The
	// defaults are 3 and 6 minutes: longer values make fewer SQS calls, but a crashed worker's messages
	// take longer to reappear. A message whose visibility cannot be kept is dropped: a waiting message
	// never reaches the handler, and a running message's handler context is cancelled with ErrVisibilityLost.
	//
	// HeartbeatExtension must be whole seconds. SQS keeps a message hidden for at most 12 hours after it
	// was received; after that it rejects extensions, so a job still running then loses its message.
	HeartbeatInterval  time.Duration
	HeartbeatExtension time.Duration
}

Options holds all configurable settings for Worker construction.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns a fully-populated Options struct with sane defaults. QueueURL is still required and must be set via WithQueueURL (or directly) before validation.

func (Options) Validate

func (o Options) Validate() error

Validate checks the Options for correctness.

type SendError added in v0.15.0

type SendError struct {
	Failed []FailedMessage
}

SendError lists the bodies SQS rejected while accepting the rest of their batch.

func (*SendError) Error added in v0.15.0

func (e *SendError) Error() string

type Sender added in v0.15.0

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

Sender sends messages to one queue. It is the producing side of Worker.

func DefaultSender added in v0.15.0

func DefaultSender(queueURL string) (*Sender, error)

DefaultSender builds a sender with a 5 second timeout and 3 total attempts.

func NewSender added in v0.15.0

func NewSender(queueURL string, timeout time.Duration, maxRetryAttempts int) (*Sender, error)

NewSender builds a sender for queueURL. timeout is the deadline for each SendMessageBatch call. maxRetryAttempts is passed to the SDK as MaxAttempts, which counts the first attempt.

func (*Sender) SendBatch added in v0.15.0

func (s *Sender) SendBatch(ctx context.Context, bodies []string) (int, error)

SendBatch sends every body, ten per SendMessageBatch call, and returns how many SQS accepted.

Bodies SQS rejects one at a time do not stop the send: the remaining batches still go, and the returned error is a *SendError naming each rejected body by its index in bodies. A failed call stops the send, and the error wraps the SDK error along with any *SendError from earlier batches. An empty body is rejected before anything is sent.

type Worker

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

func New

func New(handler HandlerFunc, optFns ...Option) (*Worker, error)

New constructs a Worker using DefaultOptions(), applies any variadic options, then validates. Handler is required. QueueURL must be provided via WithQueueURL(...).

func (*Worker) Start

func (w *Worker) Start(ctx context.Context) error

Start runs the poller, handlers, heartbeat, and background deleter until ctx is cancelled. It returns when shutdown is complete. Any poll error is returned.

The poller receives only as many messages as the worker can hold: a full batch for every idle handler, plus up to MaxPrefetched waiting for a busy one. A free handler takes up to BatchSize of the oldest waiting messages at once.

On shutdown, waiting messages are not started; the worker stops holding them, and they reappear when their visibility ends. Running handlers see ctx cancelled, and Start waits for them, keeping their messages hidden.

Jump to

Keyboard shortcuts

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