queue

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 9 Imported by: 1 module, 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

gas/queue

Test Go Reference Go Version License

Part of the Gas monorepo · Documentation · All modules

Job queues for the Gas framework, with two interchangeable stores that keep one contract, Amazon SQS's rules: Amazon SQS (or an emulator such as ElasticMQ or LocalStack), and an in-memory store for tests and local development. The interface is pull-based: consumers run their own loop and acknowledge with Ack or Nack.

Implements gas.JobQueueProvider.

go get github.com/gasmod/gas/queue
gas.WithSingletonService[gas.JobQueueProvider](sqs.New()),

Both stores take gas.ConfigProvider and gas.Logger from the container and read the queue section, or take their configuration from WithConfig; the SQS store takes its region and credentials from queue.region and the static keys, or else from the AWS SDK's default chain. Each store's Config() returns the configuration its last successful Init resolved.

Package Provides
queue The shared contract, limits and sentinel errors
queue/sqs Amazon SQS store, and emulators via a custom endpoint
queue/memory In-process store with SQS's rules, for tests and local development
queue/queuetest Recording mock of gas.JobQueueProvider

Documentation

The full documentation is on the docs site. This README is deliberately a signpost: keeping a second copy here is how the docs drifted before.

License

MIT

Documentation

Overview

Package queue defines what every queue store of the module promises: the queues it accepts, the messages it sends, how a message is leased and redelivered, how it honors a context, its lifecycle, and the errors it returns.

The rules are Amazon SQS's, so that code written against one store runs on another. The stores implement gas.JobQueueProvider and gas.Service, and each lives in its own package:

  • gas/queue/sqs: Amazon SQS, or an emulator that speaks its API.
  • gas/queue/memory: queues in the process's memory, for tests and local development.
  • gas/queue/queuetest: a mock for tests.

Usage

Each store's New returns a constructor in the shape the gas container expects, so a store is registered as gas.JobQueueProvider:

gas.WithSingletonService[gas.JobQueueProvider](sqs.New())

A producer sends, and a worker receives, handles and acknowledges:

err := q.Enqueue(ctx, "orders", []byte(`{"id":42}`),
	gas.WithJobAttributes(map[string]string{"kind": "created"}))

jobs, err := q.Dequeue(ctx, "orders", 10, 20*time.Second)
for _, job := range jobs {
	if handle(job) == nil {
		err = q.Ack(ctx, "orders", job)
	} else {
		err = q.Nack(ctx, "orders", job)
	}
}

After this the queue `orders` no longer holds the messages that were handled, and holds the others, visible again.

Contract

Every store, and any gas.JobQueueProvider that wants to be one, keeps the rules of the sections from Queue names to Order of checks.

The module's conformance tests run every store through these rules, with identical expectations, but for the differences of an emulator from SQS that a test names.

Queue names

A queue is named by a queue name or a queue URL, as ParseQueue reads it:

  • A name is 1 to 80 ASCII letters, digits, hyphens and underscores. A FIFO queue's name ends with `.fifo`.
  • A URL is `http` or `https`, has a host and no user information, query or fragment, and its path ends with a queue name.

Anything else is ErrInvalidQueue, from every method, and the error never quotes it. A queue that does not exist is ErrQueueNotFound.

Errors name a queue by its name, never by its URL, which holds the AWS account ID.

Delivery

Delivery is at least once. A message is leased, not removed, when Dequeue returns it. It stays hidden for a visibility timeout and then becomes visible again, unless Ack deletes it first.

A send whose reply is lost, and that the store or the caller retries, can store the message twice. Consumers must be idempotent.

Sending and receiving

Enqueue checks the message, as CheckMessage does, before it sends anything, and returns the first rule it breaks. A message that fails is never stored.

Dequeue returns up to maxMessages jobs, waiting up to wait for the first:

  • maxMessages is 1 to MaxMessages.
  • wait is 0 to MaxWait. A wait of 0 is a short poll, which returns at once. The wait is counted in whole seconds, rounded up.
  • Values out of bounds are ErrInvalidArgument, never clamped.
  • Dequeue returns no jobs, and no error, when none came. A store may return fewer jobs than there are messages.

Ack deletes the job's message. Nack makes it visible again at once, to be received again. Each counts as done only once it returns nil. A job without a receipt handle is ErrInvalidReceipt.

Contexts

Every method returns the context's error, wrapped, when its context has ended before it starts, and honors the context during the call.

Close is the exception: it always closes. A store whose Close context ends while calls are in flight may cut them short, as its package describes.

States

A store is not initialized until its first successful Init, and closed after Close:

  • Before its first successful Init, every method but Init and Close returns ErrNotInitialized.
  • Init on an initialized store returns ErrAlreadyInitialized and changes nothing.
  • After Close, until Init succeeds again, every method but Init and Close returns ErrClosed.
  • Close on a store that is not initialized returns nil.
  • Close then Init restarts the store.

Close refuses new calls and returns once every call in flight has returned. A Dequeue in flight when Close begins:

  • returns no jobs, no later than its wait ends;
  • returns ErrClosed, unless its receive failed first;
  • leaves no message hidden: what it received is made visible again before it returns.

Order of checks

A method checks, in this order, and returns the first failure:

  1. Its arguments, in the order of its parameters. The message of Enqueue is the exception: its rules are checked in the order CheckMessage checks them.
  2. The store's state.
  3. The context.

Payloads

A payload is text: 1 byte or more of valid UTF-8, holding only the characters SQS allows, #x9, #xA, #xD, #x20 to #xD7FF, #xE000 to #xFFFD and #x10000 to #x10FFFF. Anything else is ErrInvalidPayload. Encode binary data, such as with base64, before it is sent.

A message is at most MaxPayloadSize, 1 MiB, counting the payload and, for each attribute, its name, its value, and the 6 bytes of its type, `String`.

Message attributes

gas.WithJobAttributes sets the message's attributes, at most MaxAttributes, 10. A name:

  • is 1 to MaxAttributeNameLength, 256, ASCII letters, digits, `_`, `-` and `.`;
  • neither starts nor ends with `.`, nor holds `..`;
  • does not start with `AWS.` or `Amazon.`, in any case;
  • is not the name of an SQS system attribute, as IsReservedAttribute reports, so that no producer can pass one off as a system attribute.

The names match exactly, as SQS's are case-sensitive. A name that differs only in case, such as `sentTimestamp`, is a user attribute of its own, and a job holds it beside the system attribute.

A value is non-empty valid UTF-8 of the characters a payload may hold.

A broken rule is ErrInvalidAttribute. The error quotes neither the name nor the value, but for a system attribute's name.

Delay

gas.WithDelay hides a message for 0 to MaxDelay, 15 minutes, counted in whole seconds, rounded up, so a delay is never shorter than asked. Without one, or with 0, the queue's own delay applies, which is 0 unless the queue sets one. A delay out of bounds is ErrInvalidArgument.

System attributes

gas.Job.Attributes holds the message's attributes, then these system attributes, which take the place of an attribute of the same name that another producer sent:

  • `ApproximateReceiveCount`: how many times the message was received, this time included, such as `1`.
  • `ApproximateFirstReceiveTimestamp`: when the message was first received, in milliseconds since the Unix epoch.
  • `SentTimestamp`: when the message was sent, in milliseconds since the Unix epoch.
  • `MessageGroupId`: the group ID, when the message has one.
  • `MessageDeduplicationId`: the dedupe ID of a FIFO message.
  • `SequenceNumber`: the sequence number of a FIFO message.

SystemAttributes lists them. No other system attribute is reported.

FIFO

A queue whose name ends with `.fifo` is a FIFO queue. On it:

  • gas.WithGroupID is required. A store returns a group's messages in the order they were sent and, while a message of a group is leased, no later message of the group.
  • gas.WithDedupeID gives a dedupe ID. A message whose dedupe ID the queue saw within DedupeWindow, 5 minutes, is accepted and not stored.
  • Without a dedupe ID, a queue with content-based deduplication takes the SHA-256 of the payload, and a queue without it refuses the message.
  • A message takes no delay of its own.

A group ID and a dedupe ID are 1 to MaxIDLength, 128, ASCII letters, digits and punctuation.

On a standard queue, a group ID names the tenant of a message, as SQS's fair queues take it, and orders nothing. A dedupe ID is refused.

Every broken rule is ErrInvalidArgument.

Visibility

Dequeue leases each message for the store's VisibilityTimeout setting, or, when that is 0, for the queue's own visibility timeout. Nack ends the lease at once.

The stores also have NackAfter and Extend, which set the lease to end a duration from now, 0 to MaxVisibilityTimeout, 12 hours, rounded up to a whole second:

  • NackAfter retries later.
  • Extend keeps a long job's message hidden.

A lease never ends more than 12 hours after the receive. A duration out of bounds is ErrInvalidArgument.

Receipt handles

Nack, NackAfter and Extend need the message to be leased under the job's receipt handle. Once its lease has ended, or it was received again, the memory store returns ErrNotInFlight, and SQS replies with an error, as the sqs package describes.

Ack with the receipt handle of the latest receive deletes the message, even after its lease ended. Ack with an older handle is not an error:

  • On SQS, it may or may not delete the message.
  • On the memory store, it deletes nothing.

Lifecycle

Stop the workers that call Dequeue, and let them finish their Ack and Nack, before Close. A call after Close returns ErrClosed, and an Ack refused then leaves the message to come back when its lease ends.

The gas Worker closes services in the reverse order of their Init, so a service that depends on the queue, and runs its workers, is closed before it. A worker that is not such a service is stopped by the app before Shutdown.

Security

Payloads, attribute values and receipt handles are application data, and a queue URL holds the AWS account ID.

No error the stores make holds a payload, an attribute name or value, a group or dedupe ID, a receipt handle, a queue URL, an endpoint, or a credential. A store's errors name the operation and the queue name instead.

Concurrency

Every store is safe for concurrent use, as each store's package describes. The mock is too, except for setting its fields while it is called.

Errors

Every error a store returns starts with, in order:

  1. its service name, such as `gas/queue/memory`;
  2. the operation, such as `enqueue`;
  3. the queue name, quoted, when the identifier is valid;
  4. what failed.

It wraps one of these sentinels, to be tested with errors.Is:

The errors of this package's checks, as returned, before a store adds its service name, the operation and the queue name:

invalid queue: empty
invalid queue: not a queue name or URL
invalid payload: empty
invalid payload: not valid UTF-8
invalid payload: a character SQS does not allow, at byte 2
invalid payload: 1048577 bytes with the attributes, more than 1048576
invalid attribute: 11 attributes, at most 10
invalid attribute: a name is empty or longer than 256 bytes
invalid attribute: a name holds a character other than letters, digits, '_', '-' and '.'
invalid attribute: a name starts or ends with '.' or holds '..'
invalid attribute: a name starts with the reserved prefix AWS. or Amazon., in any case
invalid attribute: "SentTimestamp" is a system attribute
invalid attribute: a value is empty
invalid attribute: a value is not valid UTF-8
invalid attribute: a value holds a character SQS does not allow
invalid argument: delay must be 0 to 15m0s
invalid argument: a FIFO queue takes no per-message delay
invalid argument: a FIFO queue needs a group ID
invalid argument: group ID must be 1 to 128 ASCII letters, digits and punctuation
invalid argument: a standard queue takes no dedupe ID
invalid argument: dedupe ID must be 1 to 128 ASCII letters, digits and punctuation
invalid argument: maxMessages must be 1 to 10
invalid argument: wait must be 0 to 20s
invalid argument: visibility timeout must be 0 to 12h0m0s
invalid receipt handle: empty

Index

Constants

View Source
const (
	// MaxPayloadSize is the largest size of a message, in bytes: the
	// payload, plus the name, the type and the value of each attribute.
	MaxPayloadSize = 1 << 20
	// MaxAttributes is the most attributes a message carries.
	MaxAttributes = 10
	// MaxAttributeNameLength is the longest attribute name, in bytes.
	MaxAttributeNameLength = 256
	// MaxQueueNameLength is the longest queue name, in bytes.
	MaxQueueNameLength = 80
	// MaxIDLength is the longest group ID or dedupe ID, in bytes.
	MaxIDLength = 128
	// MaxDelay is the longest delay of a message.
	MaxDelay = 15 * time.Minute
	// MaxMessages is the most messages one Dequeue returns.
	MaxMessages = 10
	// MaxWait is the longest wait of one Dequeue.
	MaxWait = 20 * time.Second
	// MaxVisibilityTimeout is the longest visibility timeout.
	MaxVisibilityTimeout = 12 * time.Hour
	// DedupeWindow is how long a FIFO queue remembers a dedupe ID.
	DedupeWindow = 5 * time.Minute
)

The limits every store keeps, which are SQS's, as described in the package documentation.

View Source
const (
	// AttributeReceiveCount is how many times the message was received,
	// this time included.
	AttributeReceiveCount = "ApproximateReceiveCount"
	// AttributeFirstReceiveTimestamp is when the message was first
	// received, in milliseconds since the Unix epoch.
	AttributeFirstReceiveTimestamp = "ApproximateFirstReceiveTimestamp"
	// AttributeSentTimestamp is when the message was sent, in
	// milliseconds since the Unix epoch.
	AttributeSentTimestamp = "SentTimestamp"
	// AttributeGroupID is the message's group ID, when it has one.
	AttributeGroupID = "MessageGroupId"
	// AttributeDedupeID is the dedupe ID of a FIFO message.
	AttributeDedupeID = "MessageDeduplicationId"
	// AttributeSequenceNumber is the sequence number of a FIFO message.
	AttributeSequenceNumber = "SequenceNumber"
)

The system attributes Dequeue reports in gas.Job.Attributes, as described in the package documentation.

View Source
const FIFOSuffix = ".fifo"

FIFOSuffix ends the name of every FIFO queue, and only of those.

Variables

View Source
var (
	// ErrInvalidQueue indicates that a queue identifier is empty, or is
	// neither a queue name nor a queue URL.
	ErrInvalidQueue = errors.New("invalid queue")
	// ErrInvalidPayload indicates that a payload is empty, is not valid
	// UTF-8, holds a character SQS does not allow, or is too large.
	ErrInvalidPayload = errors.New("invalid payload")
	// ErrInvalidAttribute indicates that the attributes of a message are
	// too many, or that a name or a value breaks the attribute rules.
	ErrInvalidAttribute = errors.New("invalid attribute")
	// ErrInvalidArgument indicates that a delay, a group ID, a dedupe ID,
	// a message count, a wait or a visibility timeout is out of its
	// bounds or not allowed for the queue.
	ErrInvalidArgument = errors.New("invalid argument")
	// ErrInvalidReceipt indicates that a job's receipt handle is empty, or
	// is not one the store issued.
	ErrInvalidReceipt = errors.New("invalid receipt handle")
	// ErrQueueNotFound indicates that the queue does not exist.
	ErrQueueNotFound = errors.New("queue does not exist")
	// ErrNotInFlight indicates that a job's visibility cannot change: the
	// message is no longer leased under that receipt handle.
	ErrNotInFlight = errors.New("message not in flight")
	// ErrNotInitialized indicates that a method was called before the
	// store's first successful Init.
	ErrNotInitialized = errors.New("service not initialized")
	// ErrAlreadyInitialized indicates that Init was called on a store that
	// is initialized.
	ErrAlreadyInitialized = errors.New("service already initialized")
	// ErrClosed indicates that a method was called after Close, before
	// Init succeeded again, or that Close ended the call.
	ErrClosed = errors.New("service closed")
	// ErrNilLogger indicates that a store's constructor was given a nil
	// logger.
	ErrNilLogger = errors.New("logger is nil")
	// ErrNilConfig indicates that WithConfig was given a nil
	// configuration.
	ErrNilConfig = errors.New("config is nil")
	// ErrNoConfigProvider indicates that there is neither a configuration
	// given to WithConfig nor a ConfigProvider to bind one from.
	ErrNoConfigProvider = errors.New("no config provider")
	// ErrInvalidConfig indicates that the configuration failed to bind,
	// failed its validate tags, or broke one of the store's rules.
	ErrInvalidConfig = errors.New("invalid config")
)

The sentinel errors every store of the module shares, as described in the package documentation. A store's errors start with its own service name and the operation, and wrap one of these.

Functions

func CheckDequeue added in v0.6.0

func CheckDequeue(maxMessages int, wait time.Duration) error

CheckDequeue returns nil for the arguments of a Dequeue every store accepts, maxMessages 1 to MaxMessages and wait 0 to MaxWait, and otherwise an error wrapping ErrInvalidArgument.

func CheckMessage added in v0.6.0

func CheckMessage(q Queue, m Message) error

CheckMessage returns nil for a message every store accepts on q, and otherwise the first rule it breaks, in the order the package documentation lists them: the attributes, wrapping ErrInvalidAttribute; the payload, wrapping ErrInvalidPayload; then the delay, the group ID and the dedupe ID, wrapping ErrInvalidArgument. The error never holds the payload, an attribute name or an attribute value.

func CheckReceipt added in v0.6.0

func CheckReceipt(job gas.Job) error

CheckReceipt returns nil for a job with a receipt handle, and otherwise an error wrapping ErrInvalidReceipt.

func CheckVisibilityTimeout added in v0.6.0

func CheckVisibilityTimeout(d time.Duration) error

CheckVisibilityTimeout returns nil for a visibility timeout of NackAfter or Extend every store accepts, 0 to MaxVisibilityTimeout, and otherwise an error wrapping ErrInvalidArgument.

func IsReservedAttribute added in v0.6.0

func IsReservedAttribute(name string) bool

IsReservedAttribute reports whether name is the name of an SQS message system attribute, which no user attribute may take.

func SystemAttributes added in v0.6.0

func SystemAttributes() []string

SystemAttributes returns the names of the system attributes Dequeue reports, in the order the package documentation lists them.

func WholeSeconds added in v0.6.0

func WholeSeconds(d time.Duration) int32

WholeSeconds returns d in whole seconds, rounded up, as SQS counts a delay, a wait and a visibility timeout. It is for a d from 0 to MaxVisibilityTimeout, the largest of those.

Types

type Message added in v0.6.0

type Message struct {
	// Attributes are the user attributes, from gas.WithJobAttributes.
	Attributes map[string]string
	// GroupID is from gas.WithGroupID.
	GroupID string
	// DedupeID is from gas.WithDedupeID.
	DedupeID string
	// Payload is the message body.
	Payload []byte
	// Delay is from gas.WithDelay.
	Delay time.Duration
}

Message is what an Enqueue sends, with its options resolved.

func NewMessage added in v0.6.0

func NewMessage(payload []byte, opts []gas.EnqueueOption) Message

NewMessage returns the message of payload with opts resolved.

func (Message) Size added in v0.6.0

func (m Message) Size() int

Size returns the size of m that counts toward MaxPayloadSize: the payload, plus the name, the type and the value of each attribute.

type Queue added in v0.6.0

type Queue struct {
	// ID is the identifier as given.
	ID string
	// Name is the queue's name: ID itself, or the last path segment of a
	// URL. Errors name the queue by it.
	Name string
	// FIFO reports whether the name ends with FIFOSuffix.
	FIFO bool
	// URL reports whether ID is a queue URL.
	URL bool
}

Queue is a queue identifier, parsed.

func ParseQueue added in v0.6.0

func ParseQueue(id string) (Queue, error)

ParseQueue parses a queue identifier: a queue name, or an `http` or `https` URL with a host, without user information, a query or a fragment, whose path ends with a queue name. Otherwise it returns an error wrapping ErrInvalidQueue, which never holds id.

Directories

Path Synopsis
internal
configsrc
Package configsrc resolves a store's configuration: from a copy of the one given to the store's WithConfig option, or else by binding the store's defaults from a gas.ConfigProvider.
Package configsrc resolves a store's configuration: from a copy of the one given to the store's WithConfig option, or else by binding the store's defaults from a gas.ConfigProvider.
conformance
Package conformance holds the tests every store of the module runs: the contract of the queue package, checked with identical expectations against a store built by the caller.
Package conformance holds the tests every store of the module runs: the contract of the queue package, checked with identical expectations against a store built by the caller.
Package memory is a queue store held in the process's memory, as a gas.JobQueueProvider.
Package memory is a queue store held in the process's memory, as a gas.JobQueueProvider.
Package queuetest holds a mock of gas.JobQueueProvider, MockQueue, for tests of code that uses a queue.
Package queuetest holds a mock of gas.JobQueueProvider, MockQueue, for tests of code that uses a queue.
Package sqs is a queue store on Amazon SQS, as a gas.JobQueueProvider.
Package sqs is a queue store on Amazon SQS, as a gas.JobQueueProvider.

Jump to

Keyboard shortcuts

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