routing

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 32 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.

View Source
const CodeRoutingChanged = "routing_changed"

CodeRoutingChanged is the problem code of a save whose base version is stale: someone (or the warm-up planner) changed a stream since the edit began. Its meta "streams" lists the streams that changed.

View Source
const StreamTransactional providers.Stream = "transactional"

StreamTransactional is the fourth stream (design expansion phase 1): mail from the workspace's own product, sent through the transactional API and the SMTP relay. It fails over automatically, bulk-marketing terms don't apply to it, and on a provider it shares with Broadcasts it goes first within the provider's rate.

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 DeliveryError

func DeliveryError(key string, args i18n.Args) string

DeliveryError is why a message couldn't be delivered through its route, in English as stored. key is down, downNoOther, providersRemoved, contentGone, unreadable or allFailed.

func DeliveryErrorIn

func DeliveryErrorIn(l i18n.Lang, english string) string

DeliveryErrorIn writes why a message couldn't be delivered, stored in English, in a reader's language.

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 MailboxNameIn

func MailboxNameIn(l i18n.Lang, k string) string

MailboxNameIn is a mailbox provider's name in a reader's language: names stay as they are, "Other" is a word.

func MailboxProvider

func MailboxProvider(email string) string

MailboxProvider guesses the mailbox provider from an address's domain name. Contacts carry a better answer (internal/mailbox classifies company domains from their MX records); use it when there is one.

func NoteIn

func NoteIn(l i18n.Lang, english string) string

NoteIn writes a stored route note in a reader's language.

func Register

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

Register adds the routing operations.

func RouteNote

func RouteNote(key string, args i18n.Args) string

RouteNote is a route note in English, as the sending engine stores it. key is campaignRoute, byRule, split, splitWarmup, instead or failover.

Types

type Conditions

type Conditions struct {
	Lists            []string `json:"lists,omitempty"`
	SenderDomains    []string `json:"sender_domains,omitempty"`
	MailboxProviders []string `json:"mailbox_providers,omitempty"`
	Categories       []string `json:"categories,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. Categories (ids of transactional categories) only apply to the Transactional stream.

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
	// Available is false while the provider can't take mail (down, paused,
	// webhooks silent, disconnected): routing to it raises an issue (PR-10).
	Available bool
}

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

type MailboxClassifier

type MailboxClassifier interface {
	ForEmail(ctx context.Context, email string) mailbox.Class
}

MailboxClassifier is the part of mailbox.Classifier the route tester uses.

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
	// Category is the transactional category of the message (its id).
	Category string
}

Recipient describes the email being routed.

type RouteCampaignCondition

type RouteCampaignCondition struct {
	Field  string   `json:"field"`
	Values []string `json:"values"`
	Count  int64    `json:"count"`
}

RouteCampaignCondition counts the recipients a condition matched.

type RouteCampaignDown

type RouteCampaignDown struct {
	// Status is the provider's status (down, paused, degraded).
	Status string `json:"status"`
	// Moved go through To.
	Moved int64  `json:"moved"`
	To    string `json:"to,omitempty"`
	// Held wait for someone to decide; Reason says why they don't move.
	Held   int64  `json:"held"`
	Reason string `json:"reason,omitempty" enum:"pause_and_ask,no_fallback,warming,checks"`
	// Checks are the fallback's failed checks, in the reader's language.
	Checks []string `json:"checks"`
}

RouteCampaignDown is where a share goes while its provider can't take mail (down, paused, or its webhooks silent), as the audience build decides it: through the stream's fallback when the policy moves mail by itself and the fallback passes its checks, else nowhere, waiting.

type RouteCampaignDraft

type RouteCampaignDraft struct {
	Shares []RouteCampaignShare `json:"shares"`
	// Moved counts recipients the draft sends to another provider.
	Moved int64 `json:"moved"`
}

RouteCampaignDraft is the unsaved routing applied to the same audience.

type RouteCampaignInput

type RouteCampaignInput struct {
	Draft *RoutingSaveInput `json:"draft,omitempty"`
}

RouteCampaignInput asks for the simulation; Draft is the unsaved routing.

type RouteCampaignMailboxCap

type RouteCampaignMailboxCap struct {
	Mailbox    string `json:"mailbox"`
	Cap        int64  `json:"cap"`
	Left       int64  `json:"left"`
	Recipients int64  `json:"recipients"`
	Over       int64  `json:"over"`
}

RouteCampaignMailboxCap is one mailbox provider's part of a warming provider's cap on the send day.

type RouteCampaignResult

type RouteCampaignResult struct {
	// None is true when there's no broadcast to simulate yet.
	None        bool                     `json:"none"`
	CampaignID  string                   `json:"campaignId"`
	Name        string                   `json:"name"`
	ScheduledAt *time.Time               `json:"scheduledAt,omitempty"`
	Timezone    string                   `json:"timezone"`
	Lists       []string                 `json:"lists"`
	Domain      string                   `json:"domain"`
	Total       int64                    `json:"total"`
	Sunset      int64                    `json:"sunset"`
	Shares      []RouteCampaignShare     `json:"shares"`
	Conditions  []RouteCampaignCondition `json:"conditions"`
	Warmup      []RouteCampaignWarmup    `json:"warmup"`
	Draft       *RouteCampaignDraft      `json:"draft,omitempty"`
	// Impact is who the unsaved routing moves in the other streams (empty
	// without a draft, and for streams it doesn't change).
	Impact []RouteStreamImpact `json:"impact"`
	// Estimated is true when the audience was larger than one simulation
	// reads: Simulated recipients went through the routing and every count
	// is scaled to the whole audience (Total and Sunset are exact).
	Estimated bool  `json:"estimated"`
	Simulated int64 `json:"simulated"`
}

RouteCampaignResult is the Campaign tab.

type RouteCampaignShare

type RouteCampaignShare struct {
	ProviderID string `json:"providerId"`
	Provider   string `json:"provider"`
	Short      string `json:"short"`
	Color      string `json:"color" enum:"ses,postal,postmark,other"`
	Count      int64  `json:"count"`
	// Policy is what happens if this provider fails during the send, and
	// Fallback the provider automatic failover would use.
	Policy   string `json:"policy" enum:"automatic,pause_and_ask,warm_only"`
	Fallback string `json:"fallback,omitempty"`
	// Down is what the send would do with this share now, while the
	// provider can't take mail (review R3.U4c).
	Down *RouteCampaignDown `json:"down,omitempty"`
}

RouteCampaignShare is how many recipients a provider gets.

type RouteCampaignWarmup

type RouteCampaignWarmup struct {
	ProviderID string    `json:"providerId"`
	Provider   string    `json:"provider"`
	Day        int       `json:"day"`
	Date       time.Time `json:"date"`
	Cap        int64     `json:"cap"`
	// Left is what the cap leaves on the send day, less what went out
	// already when that day is today.
	Left int64 `json:"left"`
	// Spread: the plan caps each mailbox provider separately; MailboxCaps
	// are the parts, with the recipients each part gets.
	Spread      bool                      `json:"spread"`
	MailboxCaps []RouteCampaignMailboxCap `json:"mailboxCaps"`
	Paused      bool                      `json:"paused"`
	// Tier recipients are outside the day's engagement tiers and go
	// through TierTo instead.
	Tier   int64  `json:"tier"`
	TierTo string `json:"tierTo,omitempty"`
	// Over recipients are over the cap, or every one of them while the
	// plan is paused. To takes them when the plan allows overflow; with
	// none they wait until Resumes (the next day's cap; nil while paused,
	// until someone resumes the plan).
	Over    int64      `json:"over"`
	To      string     `json:"to,omitempty"`
	Resumes *time.Time `json:"resumes,omitempty"`
}

RouteCampaignWarmup is what a warming provider's plan does to its share on the send day (review R3.U4c), as the send would: recipients outside the day's engagement tiers go through a warm provider of their rule; the others go out up to the day's cap (per mailbox provider when the plan caps them separately); the rest goes through a warm provider when the plan allows overflow, or waits for the next day's cap (or the plan's resume) as a hold.

type RouteStreamImpact

type RouteStreamImpact struct {
	Stream    string `json:"stream" enum:"automation,system,transactional"`
	Basis     string `json:"basis" enum:"recent,contacts"`
	Addresses int64  `json:"addresses"`
	Moved     int64  `json:"moved"`
	From      string `json:"from,omitempty"`
	To        string `json:"to,omitempty"`
}

RouteStreamImpact is who an unsaved routing change moves in a stream other than Broadcasts (review R3.U4a): of the addresses the stream mailed in the last 30 days (or, when it mailed none, the workspace's contacts), how many the draft sends through another provider, and where most of them go from and to.

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,transactional"`
	ListID string `json:"listId,omitempty"`
	// Template is a transactional template's ID ("password-reset"): its
	// category decides category conditions.
	Template     string `json:"template,omitempty" maxLength:"64"`
	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"`
	// MailboxDetail names the hosting behind a company domain ("Google
	// Workspace"), found from its MX records; empty for consumer domains.
	MailboxDetail string `json:"mailboxDetail,omitempty"`
	// MX is the domain's first MX host, where the mailbox provider comes
	// from; empty when DNS didn't answer.
	MX           string            `json:"mx,omitempty"`
	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 (0–99) is where the address falls in a two-provider split: the
	// first provider listed owns the buckets below its weight. Absent for
	// other splits, which are just as sticky but have no single bucket.
	Bucket *int             `json:"bucket,omitempty"`
	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   `` /* 133-byte string literal not displayed */
	Values []string `json:"values" minItems:"1" maxItems:"50"`
	// ProviderID is the one provider the condition sends to; with Splits it
	// is the first of them.
	ProviderID string `json:"providerId,omitempty" format:"uuid"`
	// Splits, when set, split the matching recipients by weight (adding up
	// to 100) instead of sending them all to one provider.
	Splits []RoutingSplit `json:"splits,omitempty" maxItems:"5"`
	Note   string         `json:"note,omitempty" maxLength:"120"`
}

RoutingCondition is a rule evaluated before the split: IF field matches one of values THEN providerId only, or a weighted split of its own (PR-12), sticky per recipient like the stream's split.

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"`
	// Categories are the transactional categories (Transactional conditions);
	// Templates the transactional templates the route tester offers.
	Categories []RoutingNamed `json:"categories"`
	Templates  []RoutingNamed `json:"templates"`
	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(l i18n.Lang, set Set, facts map[uuid.UUID]Facts) []RoutingIssue

Validate checks a routing set against the connected providers; the issues' messages are in the reader's language.

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:"4"`
	// 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; the streams it leaves out stay exactly as they are.

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"`
	// Pushed counts the suppressions providers get: hard bounces and
	// complaints that apply to all mail (review PR-1).
	Pushed   int64      `json:"pushed"`
	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,transactional"`
	// Splits are the default route; every stream needs one except
	// Transactional, where none removes its route.
	Splits     []RoutingSplit     `json:"splits" 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"`
	// Priority (Transactional only): transactional messages go first within
	// the rate of a provider that also sends a campaign.
	Priority *bool `json:"priority,omitempty"`
	// BaseVersion is the stream's version the edit started from (the
	// stream's version in the routing read). When the stream changed since,
	// the save is refused with 409 code routing_changed and nothing is saved.
	BaseVersion string `json:"baseVersion,omitempty" maxLength:"32"`
}

RoutingStreamInput is one stream's routing in a save.

type RoutingStreamView

type RoutingStreamView struct {
	Stream string `json:"stream" enum:"broadcast,automation,system,transactional"`
	// Version changes whenever the stream's routing changes; send it back as
	// baseVersion when saving the stream.
	Version string `json:"version"`
	// Splits are in the order they were saved: the order only changes how
	// the split reads, never who goes where.
	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"`
	// Priority (Transactional only): first in line on shared providers.
	Priority *bool `json:"priority,omitempty"`
	// SenderDomains (Transactional only) are the domains marked for
	// transactional mail ("notify.acme.io").
	SenderDomains []string `json:"senderDomains,omitempty"`
	// FailoverVet is what's checked before the stream fails over: its
	// fallback, or the split's other provider (PR-14).
	FailoverVet *RoutingTargetVet `json:"failoverVet,omitempty"`
}

RoutingStreamView is one stream's saved routing.

type RoutingTargetVet

type RoutingTargetVet struct {
	ProviderID string            `json:"providerId"`
	Provider   string            `json:"provider"`
	Checks     []RoutingVetCheck `json:"checks"`
	// WarmupDay of WarmupDays while the target warms up.
	WarmupDay  int `json:"warmupDay,omitempty"`
	WarmupDays int `json:"warmupDays,omitempty"`
}

RoutingTargetVet is a failover target and its checks.

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 RoutingVetCheck

type RoutingVetCheck struct {
	Key    string `json:"key" enum:"available,bulk_terms,sandbox,domain,quota,warm"`
	Result string `json:"result" enum:"pass,warn,fail,unknown"`
	// Left is what the quota or today's warm-up cap has left.
	Left *int64 `json:"left,omitempty"`
	// Period is what a quota's Left counts: today ("day") or this month
	// ("month"); empty when the provider sets no quota.
	Period string `json:"period,omitempty" enum:"day,month"`
}

RoutingVetCheck is one check of a failover target (state.Vet).

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
	// Mailbox classifies an address that isn't a contact from its domain's
	// MX records (internal/mailbox); nil uses the domain name only.
	Mailbox MailboxClassifier
	// WarmupToday is a warming provider's allowance today, for vetting it
	// as a failover target; WarmCap its cap on a day, for the campaign
	// simulation. Both come from internal/warmup, which imports routing.
	WarmupToday func(ctx context.Context, providerID uuid.UUID) *state.WarmupToday
	WarmCap     func(ctx context.Context, providerID uuid.UUID, at time.Time) (WarmCap, bool)
	// LookupMX finds a domain's first MX host for the route tester; nil
	// asks DNS.
	LookupMX func(ctx context.Context, domain string) string
	// SimulateLimit is how many recipients a campaign simulation reads
	// before it scales to the audience (0: 200,000).
	SimulateLimit int64
}

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 and leaves the others exactly as stored. A stream sent with a baseVersion that is no longer its version is refused with 409 (CodeRoutingChanged): nothing is saved, so a tab left open never overwrites newer routing.

func (*Service) SimulateCampaign

func (s *Service) SimulateCampaign(ctx context.Context, ws *store.Workspace, in RouteCampaignInput) (RouteCampaignResult, error)

SimulateCampaign runs the next broadcast's audience through the routing, with the warm-up and failover diversions the send would make (R3.U4c).

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.

type WarmCap

type WarmCap struct {
	Cap         int64
	Left        int64
	Day         int
	Days        int
	Overflow    bool
	Paused      bool
	Tiers       []string
	MailboxCaps map[string]int64
	MailboxLeft map[string]int64
	NextDay     time.Time
}

WarmCap is a warming provider's warm-up on a day (DI from warmup, which imports routing): its cap and what is left of it, the cap's parts per mailbox provider when the plan caps them separately (gmail, outlook, yahoo, icloud, other), the engagement tiers the day sends to, whether the plan sends what's over the cap elsewhere or is paused, and when the next day's cap starts.

Jump to

Keyboard shortcuts

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