gas/queue
queue/memory
import "github.com/gasmod/gas/queue/memory"Package memory is a queue store held in the process’s memory, as a gas.JobQueueProvider. It keeps the contract of the queue package, and so the rules and limits of Amazon SQS, without a server.
It suits tests and local development. It is local to one process, and lost when the process stops. Service implements gas.Service and gas.JobQueueProvider.
In an app, the container builds the store from New and calls its Init. By hand, with a configuration given in code:
q, err := memory.New(memory.WithConfig(memory.DefaultConfig()))(nil, logger)if err != nil { return err}if err := q.Init(ctx); err != nil { return err}defer q.Close(ctx)
err = q.CreateQueue(ctx, "orders", memory.QueueConfig{})err = q.Enqueue(ctx, "orders", []byte("hello"))jobs, err := q.Dequeue(ctx, "orders", 10, 0)After this jobs holds the one message, hidden from other Dequeues for 30 seconds unless it is acked or nacked.
Configuration
Section titled “Configuration”The settings live in the queue section, in Settings:
queue.visibilitytimeout: how long a message Dequeue returns stays hidden, 1s to 12h, rounded up to a whole second, or 0 for the queue’s own. Default: DefaultVisibilityTimeout, 0.queue.maxmessages: the most messages one queue holds, and the most dedupe IDs a FIFO queue remembers, 1 or more. Default: DefaultMaxMessages, 100000.queue.maxbytes: the most bytes the messages of one queue hold, counting each payload and each attribute’s name and value, MinMaxBytes, 1 MiB, or more, so that a queue takes a message of the largest size. Default: DefaultMaxBytes, 256 MiB.
Service.Init resolves the configuration each time it runs, from one of two sources:
- Without WithConfig, it binds DefaultConfig from the
gas.ConfigProvider, which checks the
validatetags. A nil ConfigProvider is the error queue.ErrNoConfigProvider. - With WithConfig, it takes a copy of the given Config, never changing the caller’s struct, and checks the same tags. A nil Config is the error queue.ErrNilConfig.
Then the one rule the tags cannot express runs: visibilitytimeout is
0 or at least a second. A failure wraps queue.ErrInvalidConfig.
Service.Config returns a copy of the configuration the last
successful Init resolved, defaults included, or the zero Config before
one. A failed Init and Close leave it as it was. Its
visibilitytimeout is as resolved, before Init rounds it up.
Queues
Section titled “Queues”A queue exists once Service.CreateQueue creates it, as an SQS queue is created outside the app. Every other method on a queue that does not exist returns queue.ErrQueueNotFound.
A queue is named as the queue package describes. The store keys it by the whole identifier, so a URL is a name of its own, and its host is not contacted.
A QueueConfig sets:
- the queue’s own visibility timeout, 1s to 12h, or 0 for DefaultQueueVisibilityTimeout, 30 seconds, as SQS’s default;
- its delay, 0 to 15 minutes;
- on a FIFO queue, content-based deduplication.
Both durations are rounded up to a whole second. A setting out of bounds, or content-based deduplication on a standard queue, is queue.ErrInvalidArgument.
Creating a queue that exists is not an error when the configuration is the same, and is ErrQueueExists otherwise.
The queues and their messages belong to the Service, not to one Init. Close keeps them, and Init after Close finds them as Close left them, as an SQS queue outlives its clients.
Limits
Section titled “Limits”A queue holds at most maxmessages messages, counting those hidden and
those leased, and at most maxbytes bytes of them. An Enqueue past
either is ErrQueueFull.
A FIFO queue remembers at most maxmessages dedupe IDs. An Enqueue
first forgets those past the dedupe window. A new message that would
make one more is ErrQueueFull too, so that the IDs cannot grow
without bound while messages come and go.
A message stays until it is acked: the store has no retention period and no dead-letter queue. The store keeps its own copy of each payload and attribute map, and each job holds copies of its own.
Receiving
Section titled “Receiving”Dequeue looks at the queue’s messages in the order they were sent, and leases the first visible ones, up to maxMessages, each with a new receipt handle. On a FIFO queue it passes over every message of a group behind one that is not visible.
A Dequeue that finds nothing waits until the first of these:
- a message may have become visible, as Enqueue, Ack, Nack, NackAfter and Extend tell it;
- the next message it passed is due by the clock;
- its wait, counted on the system clock, ends.
Receipt handles
Section titled “Receipt handles”A receipt handle is the latest of its message while the message is leased under it and is not received again.
- Ack with the latest handle deletes the message, even when its lease has ended.
- Ack with an older handle, or one of a message already deleted, deletes nothing and is not an error. SQS can still delete in that case.
- Nack, NackAfter and Extend need the latest handle of a leased message, and otherwise return queue.ErrNotInFlight.
- A handle the store cannot have issued is queue.ErrInvalidReceipt.
The store times delays, leases, the dedupe window and the timestamps Dequeue reports by a Clock. That is the system clock unless WithClock gives another, such as one a test moves by hand to see a lease end without waiting.
The wait of a Dequeue is counted on the system clock whatever the Clock, since it is the time a caller waits. A waiting Dequeue looks again when the Clock says the next message is due, measured from the Clock’s now when it starts to wait.
Lifecycle
Section titled “Lifecycle”A successful Init opens the store and logs service initialized at
info level, with max_messages, max_bytes and visibility_timeout.
Init on an initialized store returns queue.ErrAlreadyInitialized and
changes nothing.
Service.Close runs these steps, in order:
- It makes the store closed.
- It ends every waiting Dequeue at once, which returns queue.ErrClosed.
- It waits for them to return.
- It logs
service closedat info level.
A Dequeue never holds a message it has not returned, so none is left hidden. Close ignores its context. Close on a store that is not initialized returns nil and logs nothing. Init after Close opens the store again, with a configuration resolved afresh.
Out of the initialized state:
- Before the first successful Init, every method but Init, Close, Name and Config returns an error wrapping queue.ErrNotInitialized.
- After Close, until Init succeeds, they return queue.ErrClosed.
New’s constructor fails with queue.ErrNilLogger for a nil logger. A nil ConfigProvider is accepted, and Init then requires WithConfig.
Concurrency
Section titled “Concurrency”A Service is safe for concurrent use. One mutex guards the queues and the state. Each call holds it while it works, which is short and does no I/O, and a waiting Dequeue releases it while it waits.
A call that runs beside Close either completes before it or returns queue.ErrClosed.
Errors
Section titled “Errors”The sentinel errors of this package, to be tested with errors.Is:
- ErrQueueFull: the queue holds
maxmessagesmessages, the message would take it pastmaxbytes, or a FIFO queue remembersmaxmessagesdedupe IDs within the dedupe window. - ErrQueueExists: CreateQueue found the queue with another configuration.
The other errors wrap a sentinel of the queue package, as the queue
package describes. Every error starts with ServiceName and the
operation. A configuration that fails its tags gets the validator’s
error after gas/queue/memory: init: invalid config: validate config: ,
such as:
Key: 'Config.Queue.MaxMessages' Error:Field validation for 'MaxMessages' failed on the 'min' tagThe other errors, as returned, with enqueue standing for each
operation that can fail the same way:
gas/queue/memory: logger is nilgas/queue/memory: init: config is nilgas/queue/memory: init: no config providergas/queue/memory: init: invalid config: Queue.VisibilityTimeout must be 0 or 1s to 12hgas/queue/memory: init: service already initializedgas/queue/memory: init: context canceledgas/queue/memory: enqueue: invalid queue: emptygas/queue/memory: enqueue "orders": invalid payload: emptygas/queue/memory: enqueue "orders": queue does not existgas/queue/memory: enqueue "orders": queue fullgas/queue/memory: enqueue "orders.fifo": invalid argument: a dedupe ID is needed without content-based deduplicationgas/queue/memory: enqueue "orders": service not initializedgas/queue/memory: enqueue "orders": service closedgas/queue/memory: enqueue "orders": context canceledgas/queue/memory: dequeue "orders": service closedgas/queue/memory: ack "orders": invalid receipt handle: not one this store issuedgas/queue/memory: nack "orders": message not in flightgas/queue/memory: extend "orders": invalid argument: visibility timeout must end within 12h0m0s of the receivegas/queue/memory: create queue "orders": invalid argument: delay must be 0 to 15m0sgas/queue/memory: create queue "orders": invalid argument: visibility timeout must be 0 to 12h0m0sgas/queue/memory: create queue "orders": invalid argument: a standard queue takes no content-based deduplicationgas/queue/memory: create queue "orders": queue exists with another configurationAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( // DefaultMaxMessages is the most messages a queue holds in // DefaultConfig. DefaultMaxMessages = 100000 // DefaultMaxBytes is the most bytes a queue holds in DefaultConfig: // 256 MiB. DefaultMaxBytes = 256 << 20 // MinMaxBytes is the least the MaxBytes setting allows: 1 MiB, so // that a queue takes a message of the largest size. MinMaxBytes = 1 << 20 // DefaultVisibilityTimeout is the visibility timeout of Dequeue in // DefaultConfig: 0, the queue's own. DefaultVisibilityTimeout time.Duration = 0 // DefaultQueueVisibilityTimeout is the visibility timeout of a queue // whose QueueConfig leaves it 0, as SQS's default is. DefaultQueueVisibilityTimeout = 30 * time.Second)const ServiceName = "gas/queue/memory"ServiceName is the name of the memory store, returned by Service.Name and prefixed to every error the store returns.
Variables
Section titled “Variables”var ( // ErrQueueFull indicates that Enqueue found the queue holding // MaxMessages messages, or a FIFO queue remembering MaxMessages // dedupe IDs, or that the message would take the queue past MaxBytes. ErrQueueFull = errors.New("queue full") // ErrQueueExists indicates that CreateQueue found the queue with // another configuration. ErrQueueExists = errors.New("queue exists with another configuration"))func New
Section titled “func New”func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Service, error)New returns the constructor of a Service with opts applied, in the shape the gas container expects. The constructor returns an error wrapping queue.ErrNilLogger for a nil logger; a nil ConfigProvider is accepted, and Init then requires WithConfig.
type Clock
Section titled “type Clock”type Clock interface { // Now returns the current time. Now() time.Time}Clock tells the time the store’s messages are timed by: delays, visibility timeouts, the dedupe window and the timestamps Dequeue reports. It must be safe for concurrent use.
type Config
Section titled “type Config”type Config struct { // Queue holds the settings. Queue Settings}Config holds the memory store’s configuration, read from the queue
section.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns the configuration a store starts from before binding: DefaultVisibilityTimeout, DefaultMaxMessages and DefaultMaxBytes.
type Option
Section titled “type Option”type Option func(*Service)Option configures a Service. Options only record what they are given; Init checks it.
func WithClock
Section titled “func WithClock”func WithClock(c Clock) OptionWithClock makes the store tell time by c, such as a clock a test moves by hand, as described in the package documentation. A nil c keeps the system clock.
Default: the system clock, time.Now.
func WithConfig
Section titled “func WithConfig”func WithConfig(cfg *Config) OptionWithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init copies *cfg each time it runs and never changes it; the copy is checked against its validate tags as a bound configuration is. A nil cfg makes Init fail with queue.ErrNilConfig.
Default: bind the queue section from the ConfigProvider over
DefaultConfig.
type QueueConfig
Section titled “type QueueConfig”type QueueConfig struct { // VisibilityTimeout is how long a received message stays hidden when // the store's VisibilityTimeout setting is 0: 1s to 12h, or 0 for // DefaultQueueVisibilityTimeout. It is rounded up to a whole second. VisibilityTimeout time.Duration // Delay is how long a message sent without a delay of its own stays // hidden, 0 to 15m. It is rounded up to a whole second. Delay time.Duration // ContentBasedDeduplication makes a FIFO queue take the SHA-256 of a // payload as its dedupe ID when Enqueue is given none. ContentBasedDeduplication bool}QueueConfig holds the settings of one queue, given to CreateQueue, as described in the package documentation.
type Service
Section titled “type Service”type Service struct { // contains filtered or unexported fields}Service is a queue store held in the process’s memory, as described in the package documentation. It is safe for concurrent use.
func (*Service) Ack
Section titled “func (*Service) Ack”func (s *Service) Ack(ctx context.Context, id string, job gas.Job) errorAck deletes the job’s message when job holds its latest receipt handle. A stale handle, or one of a message already deleted, deletes nothing and is not an error.
func (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(context.Context) errorClose makes every later call but Init return an error wrapping queue.ErrClosed, ends the Dequeues that wait, and waits for them to return. The queues and their messages stay. Close on a store that is not initialized returns nil and logs nothing. It ignores its context.
func (*Service) Config
Section titled “func (*Service) Config”func (s *Service) Config() ConfigConfig returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Its VisibilityTimeout is as resolved, before Init rounds it up to a whole second. Config holds no slice, map or pointer, so the copy shares nothing with the store.
func (*Service) CreateQueue
Section titled “func (*Service) CreateQueue”func (s *Service) CreateQueue(ctx context.Context, id string, cfg QueueConfig) errorCreateQueue creates the queue id with cfg, as described in the package documentation. Creating a queue that exists with the same configuration is not an error; with another, it is an error wrapping ErrQueueExists.
func (*Service) Dequeue
Section titled “func (*Service) Dequeue”func (s *Service) Dequeue( ctx context.Context, id string, maxMessages int, wait time.Duration,) ([]gas.Job, error)Dequeue receives up to maxMessages messages of the queue, waiting up to wait for the first, as described in the package documentation.
func (*Service) Enqueue
Section titled “func (*Service) Enqueue”func (s *Service) Enqueue( ctx context.Context, id string, payload []byte, opts ...gas.EnqueueOption,) errorEnqueue sends payload to the queue with opts, as described in the package documentation. On a FIFO queue, a message whose dedupe ID the queue remembers is accepted and not stored.
func (*Service) Extend
Section titled “func (*Service) Extend”func (s *Service) Extend(ctx context.Context, id string, job gas.Job, d time.Duration) errorExtend keeps the job’s message hidden for d more, 0 to 12h, rounded up to a whole second, counted from now, as described in the package documentation.
func (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(ctx context.Context) errorInit resolves the configuration and opens the store, as described in the package documentation. On an initialized store it returns queue.ErrAlreadyInitialized and changes nothing.
func (*Service) Nack
Section titled “func (*Service) Nack”func (s *Service) Nack(ctx context.Context, id string, job gas.Job) errorNack makes the job’s message visible now, as NackAfter with 0.
func (*Service) NackAfter
Section titled “func (*Service) NackAfter”func (s *Service) NackAfter(ctx context.Context, id string, job gas.Job, d time.Duration) errorNackAfter makes the job’s message visible after d, 0 to 12h, rounded up to a whole second, counted from now, as described in the package documentation.
func (*Service) Name
Section titled “func (*Service) Name”func (*Service) Name() stringName returns ServiceName.
type Settings
Section titled “type Settings”type Settings struct { // VisibilityTimeout is how long a message Dequeue returns stays // hidden: 0 is the queue's own, else 1s to 12h. VisibilityTimeout time.Duration `validate:"min=0,max=12h"` // MaxMessages is the most messages one queue holds, and the most // dedupe IDs a FIFO queue remembers, at least 1. MaxMessages int `validate:"min=1"` // MaxBytes is the most bytes the messages of one queue hold, counting // each payload and each attribute's name and value, at least // MinMaxBytes. MaxBytes int `validate:"min=1048576"`}Settings are the memory store’s settings, as described in the package documentation.