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.
Configuration
Section titled “Configuration”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
- 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
validatetags. 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.
Outbox
Section titled “Outbox”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:
- Service.Messages returns copies of the messages in the order they were sent.
- Service.Reset empties 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
maxmessagesmessages, or its message would take it pastmaxbytes. It then fails with ErrOutboxFull. - a Close canceled it, even when its gas.TemplateProvider ignored the cancellation and rendered.
Lifecycle
Section titled “Lifecycle”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:
- It makes the sender closed.
- It waits for the sends in flight, such as a SendFromTemplate that waits on its gas.TemplateProvider.
- It logs
service closedat 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.
Readiness
Section titled “Readiness”Service.CheckReady does no I/O: it fails only when the sender is not initialized or its context has ended.
Concurrency
Section titled “Concurrency”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.
Errors
Section titled “Errors”The sentinel error of this package, to be tested with errors.Is:
- ErrOutboxFull: the outbox holds
maxmessagesmessages, or the message would take it pastmaxbytes.
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 nilgas/email/memory: logger is nilgas/email/memory: config is nilgas/email/memory: init: no config providergas/email/memory: init: invalid config: Email.FromEmail must be one email addressgas/email/memory: init: service already initializedgas/email/memory: init: context canceledgas/email/memory: ready: service not initializedgas/email/memory: send: message is nilgas/email/memory: send: service not initializedgas/email/memory: send: service closedgas/email/memory: send: context canceledgas/email/memory: send: no recipientsgas/email/memory: send: outbox fullgas/email/memory: send from template: template failed: HTML "welcome.html": execute failedgas/email/memory: close: context deadline exceededAPI reference
Section titled “API reference”Constants
Section titled “Constants”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.
Variables
Section titled “Variables”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
Section titled “func New”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
Section titled “type Config”type Config struct { // Email holds the settings. Email Settings}Config holds the memory sender’s configuration, read from the email
section.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns the configuration a sender starts from before binding: no default sender, DefaultMaxMessages and DefaultMaxBytes.
type Option
Section titled “type Option”type Option func(*Service)Option configures a Service. Options only record what they are given; the constructor and Init check it.
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 the constructor fail with email.ErrNilConfig.
Default: bind the email section from the ConfigProvider over
DefaultConfig.
type Service
Section titled “type Service”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 (*Service) CheckReady
Section titled “func (*Service) CheckReady”func (s *Service) CheckReady(ctx context.Context) errorCheckReady 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 (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(ctx context.Context) errorClose 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 (*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. Config holds no slice, map or pointer, so the copy shares nothing with the sender.
func (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(ctx context.Context) errorInit 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 (*Service) Messages
Section titled “func (*Service) Messages”func (s *Service) Messages() []gas.EmailMessages 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
Section titled “func (*Service) Name”func (*Service) Name() stringName returns ServiceName.
func (*Service) Reset
Section titled “func (*Service) Reset”func (s *Service) Reset()Reset empties the outbox. It works in any state of the sender.
func (*Service) Send
Section titled “func (*Service) Send”func (s *Service) Send(ctx context.Context, msg *gas.Email) errorSend checks msg as email.CheckEmail does and stores a normalized copy of it in the outbox, as described in the package documentation.
func (*Service) SendFromTemplate
Section titled “func (*Service) SendFromTemplate”func (s *Service) SendFromTemplate(ctx context.Context, msg *gas.TemplatedEmail) errorSendFromTemplate 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
Section titled “type Settings”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.