feat(postcard): database overrides for mail templates with file fallback
- postcard owns the system_mail_* tables (postcard.Migrations), run by lagoon as the framework set summercms.postcard after system_files - Send asks an OverrideSource once per message; NewDBSource reads the customized template row through the *gorm.DB published on the app - a failed lookup, missing tables or an override that does not render or fails the safety checks sends the file version and is logged - the caller's Message.Subject still wins; Mailer, Message, NewMailer, Catalog.Register and BootPlugin keep their signatures Plan 35-01, task 2 (tracer).
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
@@ -38,24 +39,36 @@ type Options struct {
|
||||
From string
|
||||
CSS string
|
||||
BrandCSS string
|
||||
// Overrides, when set, is asked once per Send for the database
|
||||
// overrides of the template being sent. Nil sends the file versions.
|
||||
Overrides OverrideSource
|
||||
}
|
||||
|
||||
type mailer struct {
|
||||
catalog *Catalog
|
||||
driver Driver
|
||||
opts Options
|
||||
// source supplies database overrides; nil means files only.
|
||||
source OverrideSource
|
||||
// log receives override warnings and failures; nil means moduleLog.
|
||||
log *slog.Logger
|
||||
warned warnGate
|
||||
}
|
||||
|
||||
// NewMailer returns a mailer that renders from cat and delivers through driver.
|
||||
// NewMailer returns a mailer that renders from cat and delivers through
|
||||
// driver. opts.Overrides, when set, supplies database overrides per send.
|
||||
func NewMailer(cat *Catalog, driver Driver, opts Options) Mailer {
|
||||
if cat == nil {
|
||||
cat = NewCatalog()
|
||||
}
|
||||
return &mailer{catalog: cat, driver: driver, opts: opts}
|
||||
return &mailer{catalog: cat, driver: driver, opts: opts, source: opts.Overrides}
|
||||
}
|
||||
|
||||
// Send renders msg.Template and delivers it. It performs no locale selection;
|
||||
// the caller must pass the full dotted name, including any -en suffix.
|
||||
// the caller must pass the full dotted name, including any -en suffix. A
|
||||
// database override of the template is applied when the mailer has an
|
||||
// OverrideSource; an override that cannot be read or does not render is
|
||||
// logged and the file version is sent instead.
|
||||
func (m *mailer) Send(ctx context.Context, msg Message) error {
|
||||
if m == nil {
|
||||
return fmt.Errorf("postcard: mailer is nil")
|
||||
@@ -69,10 +82,7 @@ func (m *mailer) Send(ctx context.Context, msg Message) error {
|
||||
if len(msg.To) == 0 && len(msg.Cc) == 0 && len(msg.Bcc) == 0 {
|
||||
return fmt.Errorf("postcard: no recipients")
|
||||
}
|
||||
rendered, err := m.catalog.render(msg, renderOptions{
|
||||
css: m.opts.CSS,
|
||||
brandCSS: m.opts.BrandCSS,
|
||||
})
|
||||
rendered, err := m.render(ctx, msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -87,8 +97,101 @@ func (m *mailer) Send(ctx context.Context, msg Message) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// render renders msg with its database overrides applied. With no source, no
|
||||
// overrides, or overrides that fail to render or to pass the safety checks,
|
||||
// it renders the file version.
|
||||
func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, error) {
|
||||
file := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS}
|
||||
if _, err := m.catalog.lookupTemplate(msg.Template); err != nil {
|
||||
return RenderedMessage{}, err
|
||||
}
|
||||
ov := m.overrides(ctx, msg.Template)
|
||||
if ov.empty() {
|
||||
return m.catalog.render(msg, file)
|
||||
}
|
||||
with := file
|
||||
with.overrides = ov
|
||||
with.warn = m.warn
|
||||
rendered, err := m.catalog.render(msg, with)
|
||||
if err == nil {
|
||||
return rendered, nil
|
||||
}
|
||||
// The override is at fault only when the file version renders; a
|
||||
// failure of both is the caller's (a bad subject, a missing variable)
|
||||
// and is returned as before.
|
||||
rendered, fileErr := m.catalog.render(msg, file)
|
||||
if fileErr != nil {
|
||||
return RenderedMessage{}, fileErr
|
||||
}
|
||||
m.logger().Error("postcard: override failed, sending the file version",
|
||||
slog.String("template", msg.Template),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
return rendered, nil
|
||||
}
|
||||
|
||||
// overrides asks the source once. A failed lookup (no connection, tables not
|
||||
// migrated yet) is a warning, not a send failure: the file version is sent.
|
||||
func (m *mailer) overrides(ctx context.Context, template string) Overrides {
|
||||
if m.source == nil {
|
||||
return Overrides{}
|
||||
}
|
||||
ov, err := m.source.MailOverrides(ctx, template)
|
||||
if err != nil {
|
||||
m.warn(err.Error(), "postcard: mail overrides unavailable, sending the file version",
|
||||
slog.String("template", template),
|
||||
slog.String("error", err.Error()),
|
||||
)
|
||||
return Overrides{}
|
||||
}
|
||||
return ov
|
||||
}
|
||||
|
||||
func (m *mailer) logger() *slog.Logger {
|
||||
if m.log != nil {
|
||||
return m.log
|
||||
}
|
||||
return moduleLog
|
||||
}
|
||||
|
||||
// warn logs at warning level, at most once per warnInterval per key.
|
||||
func (m *mailer) warn(key, msg string, args ...any) {
|
||||
if !m.warned.allow(key, time.Now()) {
|
||||
return
|
||||
}
|
||||
m.logger().Warn(msg, args...)
|
||||
}
|
||||
|
||||
const (
|
||||
// warnInterval is how often the same override warning is repeated.
|
||||
warnInterval = time.Minute
|
||||
// warnGateSize bounds the keys a warnGate remembers.
|
||||
warnGateSize = 64
|
||||
)
|
||||
|
||||
// warnGate rate-limits warnings by key. The zero value is ready to use.
|
||||
type warnGate struct {
|
||||
mu sync.Mutex
|
||||
last map[string]time.Time
|
||||
}
|
||||
|
||||
func (g *warnGate) allow(key string, now time.Time) bool {
|
||||
g.mu.Lock()
|
||||
defer g.mu.Unlock()
|
||||
if last, ok := g.last[key]; ok && now.Sub(last) < warnInterval {
|
||||
return false
|
||||
}
|
||||
if g.last == nil || len(g.last) >= warnGateSize {
|
||||
g.last = make(map[string]time.Time)
|
||||
}
|
||||
g.last[key] = now
|
||||
return true
|
||||
}
|
||||
|
||||
// Activate publishes an app-scoped Mailer before plugin Boot. Catalog files
|
||||
// are validated later at each plugin's Boot transition.
|
||||
// are validated later at each plugin's Boot transition. The mailer reads
|
||||
// database overrides through NewDBSource, so they apply in every process
|
||||
// that publishes a *gorm.DB on app.
|
||||
func Activate[P interface{ ID() string }](app *backpack.App, _ []P) error {
|
||||
if app == nil {
|
||||
return fmt.Errorf("postcard: app is nil")
|
||||
@@ -97,10 +200,12 @@ func Activate[P interface{ ID() string }](app *backpack.App, _ []P) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Overrides = NewDBSource(app)
|
||||
m := &mailer{
|
||||
catalog: NewCatalog(),
|
||||
driver: driver,
|
||||
opts: opts,
|
||||
source: opts.Overrides,
|
||||
}
|
||||
if err := app.Publish[Mailer](m); err != nil {
|
||||
return fmt.Errorf("postcard: %w", err)
|
||||
|
||||
Reference in New Issue
Block a user