routing

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

Documentation

Overview

Package routing decides which sending provider delivers each email: rules per stream (Broadcasts, Automations, System) with conditions on the list, the sender domain and the recipient's mailbox provider, a deterministic weighted split for migrations and warm-up, a fallback per stream and the failover policy.

The decision functions here are pure; service.go stores and validates rules and policies and serves the routing screen and the route tester.

Index

Constants

View Source
const (
	Gmail   = "gmail"
	Outlook = "outlook"
	Yahoo   = "yahoo"
	ICloud  = "icloud"
	Other   = "other"
)

Mailbox providers.

View Source
const (
	IssueWeights          = "weights"
	IssueUnknownProvider  = "unknown_provider"
	IssueDuplicate        = "duplicate_provider"
	IssueFallbackIsRoute  = "fallback_in_split"
	IssueNoRoute          = "no_route"
	IssueBulkTerms        = "bulk_terms"
	IssueWarmingFallback  = "warming_fallback"
	IssueUnavailable      = "unavailable"
	IssueConditionNoValue = "condition_values"
)

RoutingIssue codes.

Variables

View Source
var MailboxProviders = []string{Gmail, Outlook, Yahoo, ICloud, Other}

MailboxProviders in display order.

Streams in display order.

Functions

func Blocking

func Blocking(issues []RoutingIssue) bool

Blocking reports whether any issue stops a save.

func Bucket

func Bucket(email string) int

Bucket maps an address to 0–99, stable across runs and machines.

func Failover

func Failover(policy Policy, fallback *uuid.UUID, state func(uuid.UUID) ProviderState) (target *uuid.UUID, hold bool)

Failover returns where a stream's mail goes when its provider is not available: the fallback (moved) or nowhere (held for a decision).

func MailboxName

func MailboxName(k string) string

MailboxName is the display name of a mailbox provider.

func MailboxProvider

func MailboxProvider(email string) string

MailboxProvider guesses the mailbox provider from an address's domain. Contacts carry a better answer (MX-based) when they exist.

func Register

func Register(h huma.API, s *Service)

Register adds the routing operations.

Types

type Conditions

type Conditions struct {
	Lists            []string `json:"lists,omitempty"`
	SenderDomains    []string `json:"sender_domains,omitempty"`
	MailboxProviders []string `json:"mailbox_providers,omitempty"`
}

Conditions restrict a rule; an empty set is the stream's default rule. Values within a field are OR-ed, fields are AND-ed.

func (Conditions) Empty

func (c Conditions) Empty() bool

Empty reports whether the conditions match everything.

type Decision

type Decision struct {
	ProviderID uuid.UUID
	Rule       Rule
	// Matched is the condition field that decided ("mailbox_provider",
	// "list", "sender_domain"), empty for the default rule.
	Matched      string
	MatchedValue string
	// Bucket is the recipient's hash bucket (0–99) when a weighted split decided.
	Bucket   int
	Split    bool
	Fallback *uuid.UUID
	Policy   Policy
}

Decision is where a recipient goes and why.

type Facts

type Facts struct {
	ID          uuid.UUID
	Name        string
	Short       string
	Adapter     string
	Status      string
	Bulk        providers.BulkPolicy
	BulkAllowed bool
	// BroadcastStreamCreatable is true when ReputeCast can create the
	// stream that makes bulk mail allowed (Postmark).
	BroadcastStreamCreatable bool
	WarmingUp                bool
	WarmupDay                int
	WarmupDays               int
}

Facts is what validation needs to know about a connected provider.

type Policy

type Policy string

Policy is a stream's failover policy.

const (
	// Automatic switches to the fallback when the primary fails.
	Automatic Policy = "automatic"
	// PauseAndAsk holds the remaining recipients and asks a person.
	PauseAndAsk Policy = "pause_and_ask"
	// WarmOnly fails over automatically, but only to a provider that is not
	// warming up; otherwise it behaves like PauseAndAsk.
	WarmOnly Policy = "warm_only"
)

Failover policies.

func DefaultPolicy

func DefaultPolicy(s providers.Stream) Policy

DefaultPolicy is the failover policy of a stream nobody configured: pause-and-ask for Broadcasts (moving a bulk send to a cold provider mid-send can hurt reputation), automatic for System and Automations.

func (Policy) Valid

func (p Policy) Valid() bool

Valid reports whether p is a known policy.

type ProviderState

type ProviderState struct {
	Available bool // healthy enough to send (not down, webhooks not silent)
	WarmingUp bool
}

ProviderState is what failover needs to know about a provider.

type Recipient

type Recipient struct {
	Stream          providers.Stream
	Email           string
	Lists           []string
	SenderDomain    string
	MailboxProvider string // gmail, outlook, yahoo, icloud, other; derived from Email when empty
}

Recipient describes the email being routed.

type RouteTestCost

type RouteTestCost struct {
	Basis      string   `json:"basis" enum:"metered,plan,self_hosted"`
	PerMessage *float64 `json:"perMessage,omitempty"`
	Per1000    *float64 `json:"per1000,omitempty"`
}

RouteTestCost is what one message costs on the chosen provider.

type RouteTestFallback

type RouteTestFallback struct {
	Policy   string `json:"policy" enum:"automatic,pause_and_ask,warm_only"`
	Provider string `json:"provider,omitempty"`
	Short    string `json:"short,omitempty"`
}

RouteTestFallback says what happens if the provider fails.

type RouteTestInput

type RouteTestInput struct {
	Stream       string `json:"stream" enum:"broadcast,automation,system"`
	ListID       string `json:"listId,omitempty"`
	SenderDomain string `json:"senderDomain,omitempty" maxLength:"253"`
	Email        string `json:"email" minLength:"3" maxLength:"254"`
	// Draft tests unsaved routing instead of the saved one.
	Draft *RoutingSaveInput `json:"draft,omitempty"`
}

RouteTestInput asks which provider would send an email.

type RouteTestResult

type RouteTestResult struct {
	ProviderID      string            `json:"providerId"`
	Provider        string            `json:"provider"`
	Short           string            `json:"short"`
	Color           string            `json:"color" enum:"ses,postal,postmark,other"`
	MailboxProvider string            `json:"mailboxProvider"`
	DKIMSelector    string            `json:"dkimSelector"`
	Cost            RouteTestCost     `json:"cost"`
	Steps           []RouteTestStep   `json:"steps"`
	Fallback        RouteTestFallback `json:"fallback"`
	Suppressed      bool              `json:"suppressed"`
	// Held is true when the provider can't take mail right now.
	Held bool `json:"held"`
}

RouteTestResult answers "Which provider would send this email?".

type RouteTestSplit

type RouteTestSplit struct {
	Short  string `json:"short"`
	Weight int    `json:"weight"`
}

RouteTestSplit is one provider of a weighted split, for the step text.

type RouteTestStep

type RouteTestStep struct {
	// Kind: stream, condition, split, primary, suppression, held.
	Kind     string           `json:"kind" enum:"stream,condition,split,primary,suppression,held"`
	Stream   string           `json:"stream,omitempty"`
	Field    string           `json:"field,omitempty"`
	Value    string           `json:"value,omitempty"`
	Provider string           `json:"provider,omitempty"`
	Bucket   int              `json:"bucket"`
	Splits   []RouteTestSplit `json:"splits,omitempty"`
	// Conditions is how many conditions the stream has (stream step).
	Conditions int `json:"conditions"`
	// Warming names a provider of the default split that is warming up
	// ("Postal is still warming up").
	Warming    string `json:"warming,omitempty"`
	Suppressed bool   `json:"suppressed"`
	Email      string `json:"email,omitempty"`
	Reason     string `json:"reason,omitempty"`
}

RouteTestStep is one step of the decision, in order.

type RoutingCondition

type RoutingCondition struct {
	Field      string   `json:"field" enum:"mailbox_provider,list,sender_domain"`
	Values     []string `json:"values" minItems:"1" maxItems:"50"`
	ProviderID string   `json:"providerId" format:"uuid"`
	Note       string   `json:"note,omitempty" maxLength:"120"`
}

RoutingCondition is a rule evaluated before the split: IF field matches one of values THEN only providerId.

type RoutingConditionView

type RoutingConditionView struct {
	RoutingCondition
	ValueLabels []string `json:"valueLabels"`
}

RoutingConditionView is a condition with readable values.

type RoutingConfig

type RoutingConfig struct {
	Streams       []RoutingStreamView `json:"streams"`
	Providers     []RoutingProvider   `json:"providers"`
	Lists         []RoutingNamed      `json:"lists"`
	SenderDomains []string            `json:"senderDomains"`
	SavedAt       *time.Time          `json:"savedAt,omitempty"`
	SavedBy       string              `json:"savedBy"`
	Issues        []RoutingIssue      `json:"issues"`
	Shared        RoutingShared       `json:"shared"`
}

RoutingConfig is the routing screen.

type RoutingIssue

type RoutingIssue struct {
	Code       string `json:"code"`
	Stream     string `json:"stream"`
	Field      string `json:"field,omitempty"`
	ProviderID string `json:"providerId,omitempty"`
	Message    string `json:"message"`
	Blocking   bool   `json:"blocking"`
}

RoutingIssue is a problem with a routing set. Blocking issues stop a save; the others are warnings shown next to the route.

func Validate

func Validate(set Set, facts map[uuid.UUID]Facts) []RoutingIssue

Validate checks a routing set against the connected providers.

type RoutingNamed

type RoutingNamed struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

RoutingNamed is a list or sender domain option.

type RoutingProvider

type RoutingProvider struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Short       string `json:"short"`
	Label       string `json:"label"`
	Adapter     string `json:"adapter"`
	Color       string `json:"color" enum:"ses,postal,postmark,other"`
	Status      string `json:"status"`
	Bulk        string `json:"bulk" enum:"allowed,broadcast_streams_only,forbidden,your_policy"`
	BulkAllowed bool   `json:"bulkAllowed"`
	// BroadcastStreamCreatable: ReputeCast can create the stream that makes
	// bulk mail allowed ("Postmark · Broadcast stream (create)").
	BroadcastStreamCreatable bool `json:"broadcastStreamCreatable"`
	// RemovesWebhook: removing the provider also removes the webhook
	// ReputeCast registered there.
	RemovesWebhook bool               `json:"removesWebhook"`
	WarmingUp      bool               `json:"warmingUp"`
	WarmupDay      int                `json:"warmupDay,omitempty"`
	WarmupDays     int                `json:"warmupDays,omitempty"`
	ShareSteps     []RoutingShareStep `json:"shareSteps"`
	Terms          []RoutingTerms     `json:"terms"`
}

RoutingProvider is a provider that can be picked in the routing selects.

type RoutingSaveInput

type RoutingSaveInput struct {
	Streams []RoutingStreamInput `json:"streams" minItems:"1" maxItems:"3"`
	// AcknowledgeBulkTerms keeps a Broadcast route that a provider's terms
	// don't allow. The decision is recorded and Send Readiness blocks
	// broadcasts while it stands.
	AcknowledgeBulkTerms bool `json:"acknowledgeBulkTerms,omitempty"`
}

RoutingSaveInput replaces the routing of the streams it lists.

type RoutingShareStep

type RoutingShareStep struct {
	Day   int `json:"day"`
	Share int `json:"share"`
}

RoutingShareStep is a planned increase of a warming provider's Broadcast share.

type RoutingShared

type RoutingShared struct {
	Suppressions int64      `json:"suppressions"`
	SyncedAt     *time.Time `json:"syncedAt,omitempty"`
}

RoutingShared is the "Shared across providers" card.

type RoutingSplit

type RoutingSplit struct {
	ProviderID string `json:"providerId" format:"uuid"`
	Weight     int    `json:"weight" minimum:"0" maximum:"100"`
}

RoutingSplit is one provider's share.

type RoutingStreamInput

type RoutingStreamInput struct {
	Stream     string             `json:"stream" enum:"broadcast,automation,system"`
	Splits     []RoutingSplit     `json:"splits" minItems:"1" maxItems:"5"`
	Fallback   string             `json:"fallback,omitempty" doc:"Provider id, or empty for none"`
	Failover   string             `json:"failover" enum:"automatic,pause_and_ask,warm_only"`
	Conditions []RoutingCondition `json:"conditions" maxItems:"20"`
}

RoutingStreamInput is one stream's routing in a save.

type RoutingStreamView

type RoutingStreamView struct {
	Stream     string                 `json:"stream" enum:"broadcast,automation,system"`
	Splits     []RoutingSplit         `json:"splits"`
	Fallback   string                 `json:"fallback"`
	Failover   string                 `json:"failover" enum:"automatic,pause_and_ask,warm_only"`
	Conditions []RoutingConditionView `json:"conditions"`
	// BulkTermsAcknowledgedAt is set while someone chose to keep a Broadcast
	// route the provider's terms don't allow.
	BulkTermsAcknowledgedAt *time.Time     `json:"bulkTermsAcknowledgedAt,omitempty"`
	Volume                  *RoutingVolume `json:"volume,omitempty"`
}

RoutingStreamView is one stream's saved routing.

type RoutingTerms

type RoutingTerms struct {
	Variant string   `json:"variant"`
	Bulk    string   `json:"bulk" enum:"allowed,broadcast_streams_only,forbidden,your_policy"`
	Note    string   `json:"note"`
	Streams []string `json:"streams"`
	// Active marks the variant this connection uses; Available is false for
	// a variant that isn't set up yet (Postmark Broadcast stream).
	Active    bool `json:"active"`
	Available bool `json:"available"`
}

RoutingTerms is one row of "What each connected provider's terms allow".

type RoutingVolume

type RoutingVolume struct {
	Count int64  `json:"count"`
	Per   string `json:"per" enum:"day,week"`
	// Smallest and Largest are the audience range of recent broadcasts.
	Smallest int64 `json:"smallest,omitempty"`
	Largest  int64 `json:"largest,omitempty"`
}

RoutingVolume is how much mail a stream carries.

type Rule

type Rule struct {
	ID         uuid.UUID
	Stream     providers.Stream
	Priority   int
	Name       string
	Conditions Conditions
	Splits     []Split
	Fallback   *uuid.UUID
	Enabled    bool
}

Rule is one routing rule of a stream.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Now   func() time.Time
}

Service stores routing and serves the routing screen.

func (*Service) Get

Get returns the routing screen for a workspace.

func (*Service) Route

func (s *Service) Route(ctx context.Context, wsID uuid.UUID, r Recipient) (Decision, bool, error)

Route decides the provider for one recipient with the saved rules. The sending pipeline and the system mailer use it.

func (*Service) Save

Save replaces the routing of the streams in the input.

func (*Service) Test

Test runs the route tester for one address.

type Set

type Set struct {
	Rules    []Rule
	Policies map[providers.Stream]Policy
}

Set is a workspace's routing: rules by priority and a policy per stream.

func Load

func Load(ctx context.Context, q *store.Queries, wsID uuid.UUID) (Set, error)

Load reads a workspace's routing set.

func (Set) Default

func (s Set) Default(stream providers.Stream) (Rule, bool)

Default returns the stream's default rule (no conditions), if any.

func (Set) Policy

func (s Set) Policy(stream providers.Stream) Policy

Policy returns the failover policy of a stream.

func (Set) Resolve

func (s Set) Resolve(r Recipient) (Decision, bool)

Resolve applies the stream's rules to a recipient. ok is false when the stream has no rule (no provider is set up for it).

func (Set) StreamRules

func (s Set) StreamRules(stream providers.Stream) []Rule

StreamRules returns a stream's enabled rules in evaluation order: conditional rules by priority, then the default rule.

type Split

type Split struct {
	ProviderID uuid.UUID `json:"provider_id"`
	Weight     int       `json:"weight"`
}

Split is one provider's share of a rule, in percent.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL