## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# queue/memory

> Package memory is a queue store held in the process's memory, as a gas.JobQueueProvider.

The Markdown of https://gasmod.dev/reference/queue/memory/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
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](#Service) implements gas.Service and
gas.JobQueueProvider.

## Usage

In an app, the container builds the store from [New](#New) and calls its
Init. By hand, with a configuration given in code:

```go
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

The settings live in the `queue` section, in [Settings](#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](#DefaultVisibilityTimeout), 0.
- `queue.maxmessages`: the most messages one queue holds, and the
most dedupe IDs a FIFO queue remembers, 1 or more. Default:
[DefaultMaxMessages](#DefaultMaxMessages), 100000.
- `queue.maxbytes`: the most bytes the messages of one queue hold,
counting each payload and each attribute's name and value,
[MinMaxBytes](#MinMaxBytes), 1 MiB, or more, so that a queue takes a message of
the largest size. Default: [DefaultMaxBytes](#DefaultMaxBytes), 256 MiB.

[Service.Init](#Service.Init) resolves the configuration each time it runs, from one
of two sources:

- Without [WithConfig](#WithConfig), it binds [DefaultConfig](#DefaultConfig) from the
gas.ConfigProvider, which checks the `validate` tags. 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](#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

A queue exists once [Service.CreateQueue](#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](#QueueConfig) sets:

- the queue's own visibility timeout, 1s to 12h, or 0 for
[DefaultQueueVisibilityTimeout](#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](#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

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](#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](#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

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

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.

## Clock

The store times delays, leases, the dedupe window and the timestamps
Dequeue reports by a [Clock](#Clock). That is the system clock unless
[WithClock](#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

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](#Service.Close) runs these steps, in order:

1. It makes the store closed.
2. It ends every waiting Dequeue at once, which returns
queue.ErrClosed.
3. It waits for them to return.
4. It logs `service closed` at 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](#New)'s constructor fails with queue.ErrNilLogger for a nil logger. A
nil ConfigProvider is accepted, and Init then requires WithConfig.

## 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

The sentinel errors of this package, to be tested with [errors.Is](https://pkg.go.dev/errors#Is):

- [ErrQueueFull](#ErrQueueFull): the queue holds `maxmessages` messages, the message
would take it past `maxbytes`, or a FIFO queue remembers
`maxmessages` dedupe IDs within the dedupe window.
- [ErrQueueExists](#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](#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:

```go
Key: 'Config.Queue.MaxMessages' Error:Field validation for 'MaxMessages' failed on the 'min' tag
```

The other errors, as returned, with `enqueue` standing for each
operation that can fail the same way:

```go
gas/queue/memory: logger is nil
gas/queue/memory: init: config is nil
gas/queue/memory: init: no config provider
gas/queue/memory: init: invalid config: Queue.VisibilityTimeout must be 0 or 1s to 12h
gas/queue/memory: init: service already initialized
gas/queue/memory: init: context canceled
gas/queue/memory: enqueue: invalid queue: empty
gas/queue/memory: enqueue "orders": invalid payload: empty
gas/queue/memory: enqueue "orders": queue does not exist
gas/queue/memory: enqueue "orders": queue full
gas/queue/memory: enqueue "orders.fifo": invalid argument: a dedupe ID is needed without content-based deduplication
gas/queue/memory: enqueue "orders": service not initialized
gas/queue/memory: enqueue "orders": service closed
gas/queue/memory: enqueue "orders": context canceled
gas/queue/memory: dequeue "orders": service closed
gas/queue/memory: ack "orders": invalid receipt handle: not one this store issued
gas/queue/memory: nack "orders": message not in flight
gas/queue/memory: extend "orders": invalid argument: visibility timeout must end within 12h0m0s of the receive
gas/queue/memory: create queue "orders": invalid argument: delay must be 0 to 15m0s
gas/queue/memory: create queue "orders": invalid argument: visibility timeout must be 0 to 12h0m0s
gas/queue/memory: create queue "orders": invalid argument: a standard queue takes no content-based deduplication
gas/queue/memory: create queue "orders": queue exists with another configuration
```


## API reference

### Constants

<a id="DefaultMaxMessages"></a><a id="DefaultMaxBytes"></a><a id="MinMaxBytes"></a><a id="DefaultVisibilityTimeout"></a><a id="DefaultQueueVisibilityTimeout"></a>

```go
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
)
```

<a id="ServiceName"></a>

```go
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

<a id="ErrQueueFull"></a><a id="ErrQueueExists"></a>

```go
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")
)
```

<a id="New"></a>

#### func New

```go
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.

<a id="Clock"></a><a id="Clock.Now"></a>

### type Clock

```go
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.

<a id="Config"></a>

### type Config

```go
type Config struct {
	// Queue holds the settings.
	Queue Settings
}
```

Config holds the memory store's configuration, read from the `queue`
section.

<a id="DefaultConfig"></a>

#### func DefaultConfig

```go
func DefaultConfig() *Config
```

DefaultConfig returns the configuration a store starts from before
binding: DefaultVisibilityTimeout, DefaultMaxMessages and
DefaultMaxBytes.

<a id="Option"></a>

### type Option

```go
type Option func(*Service)
```

Option configures a Service. Options only record what they are given;
Init checks it.

<a id="WithClock"></a>

#### func WithClock

```go
func WithClock(c Clock) Option
```

WithClock 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.

<a id="WithConfig"></a>

#### func WithConfig

```go
func WithConfig(cfg *Config) Option
```

WithConfig 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.

<a id="QueueConfig"></a>

### type QueueConfig

```go
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.

<a id="Service"></a>

### type Service

```go
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.

<a id="Service.Ack"></a>

#### func (*Service) Ack

```go
func (s *Service) Ack(ctx context.Context, id string, job gas.Job) error
```

Ack 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.

<a id="Service.Close"></a>

#### func (*Service) Close

```go
func (s *Service) Close(context.Context) error
```

Close 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.

<a id="Service.Config"></a>

#### func (*Service) Config

```go
func (s *Service) Config() Config
```

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 to a whole second. Config holds no
slice, map or pointer, so the copy shares nothing with the store.

<a id="Service.CreateQueue"></a>

#### func (*Service) CreateQueue

```go
func (s *Service) CreateQueue(ctx context.Context, id string, cfg QueueConfig) error
```

CreateQueue 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.

<a id="Service.Dequeue"></a>

#### func (*Service) Dequeue

```go
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.

<a id="Service.Enqueue"></a>

#### func (*Service) Enqueue

```go
func (s *Service) Enqueue(
	ctx context.Context,
	id string,
	payload []byte,
	opts ...gas.EnqueueOption,
) error
```

Enqueue 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.

<a id="Service.Extend"></a>

#### func (*Service) Extend

```go
func (s *Service) Extend(ctx context.Context, id string, job gas.Job, d time.Duration) error
```

Extend 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.

<a id="Service.Init"></a>

#### func (*Service) Init

```go
func (s *Service) Init(ctx context.Context) error
```

Init resolves the configuration and opens the store, as described in
the package documentation. On an initialized store it returns
queue.ErrAlreadyInitialized and changes nothing.

<a id="Service.Nack"></a>

#### func (*Service) Nack

```go
func (s *Service) Nack(ctx context.Context, id string, job gas.Job) error
```

Nack makes the job's message visible now, as NackAfter with 0.

<a id="Service.NackAfter"></a>

#### func (*Service) NackAfter

```go
func (s *Service) NackAfter(ctx context.Context, id string, job gas.Job, d time.Duration) error
```

NackAfter 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.

<a id="Service.Name"></a>

#### func (*Service) Name

```go
func (*Service) Name() string
```

Name returns ServiceName.

<a id="Settings"></a>

### type Settings

```go
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.
