Skip to content
Gasv0.10.0

gas/email

email/memory

import "github.com/gasmod/gas/email/memory"

Package memory is an email sender that sends nothing: it keeps each message in an outbox in the process’s memory, for tests and local development, as a gas.EmailProvider.

Service implements gas.Service, gas.EmailProvider and gas.ReadyReporter, and keeps the contract of the email package. It has the same rules and the same template rendering as gas/email/ses, so a message the memory sender accepts is one the SES sender would send.

In an app, the container builds the sender from New and calls its Init. By hand, with a configuration given in code:

cfg := memory.DefaultConfig()
cfg.Email.FromEmail = "Shop <shop@example.com>"
m, err := memory.New(memory.WithConfig(cfg))(templates, nil, logger)
if err != nil {
return err
}
if err := m.Init(ctx); err != nil {
return err
}
defer m.Close(ctx)
err = m.Send(ctx, &gas.Email{
To: []string{"alice@example.com"},
Subject: "Your order",
TextBody: "It ships today.",
})
sent := m.Messages()

After this sent holds one message, from Shop <shop@example.com> to alice@example.com.

The settings live in the email section, in Settings:

  • email.fromemail: the sender of a message whose From is empty, one email address as the email package reads one, which Init normalizes. Default: none, so every message needs a From.
  • email.maxmessages: the most messages the outbox holds, at least
  1. Default: DefaultMaxMessages (10000).
  • email.maxbytes: the most bytes the messages of the outbox hold, each counted as email.MessageSize estimates it, at least MinMaxBytes (1 MiB). 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 validate tags. A nil ConfigProvider is the error email.ErrNoConfigProvider.
  • With WithConfig, it takes a copy of the given Config, never changing the caller’s struct, and checks the same tags.

Then fromemail, when set, must be one email address. A failure wraps email.ErrInvalidConfig and names the setting, never its value.

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 fromemail is the normalized address.

A send that keeps every rule stores a copy of the normalized message CheckEmail returns, which shares nothing with the caller’s. It holds From and the other addresses as the email package normalizes them, an empty list as nil, and the headers.

The subject is kept as given, not encoded as the SES sender sends one that is not ASCII. The sender logs no message, and no part of one.

To read and empty the outbox:

Both work in any state of the sender, and the outbox outlives Close and a restart.

A send stores nothing when:

  • it finds the outbox holding maxmessages messages, or its message would take it past maxbytes. It then fails with ErrOutboxFull.
  • a Close canceled it, even when its gas.TemplateProvider ignored the cancellation and rendered.

A successful Init logs service initialized at info level with from, whether a default sender is set, max_messages and max_bytes. Init on an initialized sender returns email.ErrAlreadyInitialized and changes nothing. A failed Init leaves the sender as it was.

Service.Close runs these steps, in order:

  1. It makes the sender closed.
  2. It waits for the sends in flight, such as a SendFromTemplate that waits on its gas.TemplateProvider.
  3. It logs service closed at info level.

When its context ends first, Close cancels the sends in flight, logs service closed, sends in flight canceled at warn level, and returns an error wrapping the context’s error. Close on a sender that is not initialized returns nil and logs nothing.

New’s constructor fails with:

  • email.ErrNilTemplates for a nil gas.TemplateProvider;
  • email.ErrNilLogger for a nil logger;
  • email.ErrNilConfig for WithConfig(nil).

A nil ConfigProvider is accepted, and Init then requires WithConfig.

Service.CheckReady does no I/O: it fails only when the sender is not initialized or its context has ended.

A Service is safe for concurrent use. Init and Close run one at a time. The outbox is kept under a lock, which no send holds while it renders.

The sentinel error of this package, to be tested with errors.Is:

  • ErrOutboxFull: the outbox holds maxmessages messages, or the message would take it past maxbytes.

The other errors wrap a sentinel of the email package, as the email package describes. Every error starts with ServiceName and the operation, send standing below for both send operations:

gas/email/memory: template provider is nil
gas/email/memory: logger is nil
gas/email/memory: config is nil
gas/email/memory: init: no config provider
gas/email/memory: init: invalid config: Email.FromEmail must be one email address
gas/email/memory: init: service already initialized
gas/email/memory: init: context canceled
gas/email/memory: ready: service not initialized
gas/email/memory: send: message is nil
gas/email/memory: send: service not initialized
gas/email/memory: send: service closed
gas/email/memory: send: context canceled
gas/email/memory: send: no recipients
gas/email/memory: send: outbox full
gas/email/memory: send from template: template failed: HTML "welcome.html": execute failed
gas/email/memory: close: context deadline exceeded

const (
// DefaultMaxMessages is the most messages the outbox holds in
// DefaultConfig.
DefaultMaxMessages = 10000
// DefaultMaxBytes is the most bytes the outbox holds in
// DefaultConfig: 256 MiB.
DefaultMaxBytes = 256 << 20
// MinMaxBytes is the least the MaxBytes setting allows: 1 MiB.
MinMaxBytes = 1 << 20
)

const ServiceName = "gas/email/memory"

ServiceName is the name of the memory sender, returned by Service.Name and prefixed to every error the sender returns.

var ErrOutboxFull = errors.New("outbox full")

ErrOutboxFull indicates that a send found the outbox holding MaxMessages messages, or that its message would take the outbox past MaxBytes.

func New(
opts ...Option,
) func(gas.TemplateProvider, 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 email.ErrNilTemplates for a nil TemplateProvider, email.ErrNilLogger for a nil logger, and email.ErrNilConfig for WithConfig(nil); a nil ConfigProvider is accepted, and Init then requires WithConfig.

type Config struct {
// Email holds the settings.
Email Settings
}

Config holds the memory sender’s configuration, read from the email section.

func DefaultConfig() *Config

DefaultConfig returns the configuration a sender starts from before binding: no default sender, DefaultMaxMessages and DefaultMaxBytes.

type Option func(*Service)

Option configures a Service. Options only record what they are given; the constructor and Init check it.

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 the constructor fail with email.ErrNilConfig.

Default: bind the email section from the ConfigProvider over DefaultConfig.

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

Service is an email sender that keeps what it sends in an outbox in the process’s memory, as described in the package documentation. It is safe for concurrent use.

func (s *Service) CheckReady(ctx context.Context) error

CheckReady reports readiness without I/O: an error wrapping email.ErrNotInitialized or email.ErrClosed when the sender is not initialized, the context’s error when ctx has ended, and else nil.

func (s *Service) Close(ctx context.Context) error

Close makes every later call but Init return an error wrapping email.ErrClosed, and waits for every send in flight to return, as described in the package documentation. When ctx ends first, it cancels the sends in flight, which return email.ErrClosed, and returns an error wrapping ctx’s error. The outbox stays. Close on a sender that is not initialized returns nil and logs nothing.

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. Config holds no slice, map or pointer, so the copy shares nothing with the sender.

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

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

func (s *Service) Messages() []gas.Email

Messages returns copies of the messages in the outbox, in the order they were sent, as normalized: changing what it returns changes no message of the outbox. It works in any state of the sender.

func (*Service) Name() string

Name returns ServiceName.

func (s *Service) Reset()

Reset empties the outbox. It works in any state of the sender.

func (s *Service) Send(ctx context.Context, msg *gas.Email) error

Send checks msg as email.CheckEmail does and stores a normalized copy of it in the outbox, as described in the package documentation.

func (s *Service) SendFromTemplate(ctx context.Context, msg *gas.TemplatedEmail) error

SendFromTemplate renders msg into a copy, as the email package describes under Templates, and sends the copy as Send does. It never changes msg.

type Settings struct {
// FromEmail is the sender of a message whose From is empty; empty is
// none.
FromEmail string
// MaxMessages is the most messages the outbox holds, at least 1.
MaxMessages int `validate:"min=1"`
// MaxBytes is the most bytes the messages of the outbox hold, each
// counted as email.MessageSize estimates it, at least MinMaxBytes.
MaxBytes int `validate:"min=1048576"`
}

Settings are the memory sender’s settings, as described in the package documentation.