Documentation
¶
Overview ¶
Package engine is ReputeCast's sending engine (spec 5.3, 7.6): it builds a campaign's recipient list, routes, renders and hands every message to its sending provider within rate limits and throttles, watches bounce, complaint and outage signals and pauses what they concern, sends automation emails, and serves the live monitor's snapshot and stream. Providers marked "demo": true go through the simulated transport.
Index ¶
- Constants
- Variables
- func LinkVar(position int) string
- func MaskAddress(email string) string
- func Register(h huma.API, e *Engine)
- func RegisterJobs(reg *jobs.Registry, e *Engine)
- func RegisterTraffic(h huma.API, e *Engine)
- func RegisterTransactional(reg *jobs.Registry, o *TransactionalOutbox)
- func SeedMailboxOrder(keys []string) []string
- type AutomationMailer
- type CanaryGate
- type CanaryIP
- type CanaryPlan
- type ComplaintWatchArgs
- type ComplaintWatchWorker
- type Conditional
- type Content
- type DemoSendOptions
- type DemoSendResult
- type Engine
- func (e *Engine) Acknowledge(ctx context.Context, campaignID, by, incidentID uuid.UUID) error
- func (e *Engine) CanaryPlanFor(ctx context.Context, campaignID uuid.UUID) (CanaryPlan, error)
- func (e *Engine) Cancel(ctx context.Context, campaignID, by uuid.UUID) error
- func (e *Engine) CancelShare(ctx context.Context, campaignID, by uuid.UUID, mailbox string, ...) (int64, error)
- func (e *Engine) ContinueCanary(ctx context.Context, campaignID, by uuid.UUID) error
- func (e *Engine) DemoSend(ctx context.Context, o DemoSendOptions) (DemoSendResult, error)
- func (e *Engine) Drive(ctx context.Context, campaignID uuid.UUID, start time.Time, d time.Duration) (time.Time, bool, error)
- func (e *Engine) DrivePrepare(ctx context.Context, campaignID uuid.UUID, now time.Time) error
- func (e *Engine) Estimate(ctx context.Context, campaignID uuid.UUID, o EstimateOptions) (Estimate, error)
- func (e *Engine) ExtendCanary(ctx context.Context, campaignID, by uuid.UUID) error
- func (e *Engine) HoldShares(ctx context.Context, providerID uuid.UUID, reason string) error
- func (e *Engine) InDoubtHook() ingest.MessageHook
- func (e *Engine) KickAutomationOutbox()
- func (e *Engine) MoveShare(ctx context.Context, campaignID, by, from, to uuid.UUID) (int64, error)
- func (e *Engine) OutboxStep(ctx context.Context, now time.Time) (int, error)
- func (e *Engine) Pause(ctx context.Context, campaignID, by uuid.UUID, reason string) error
- func (e *Engine) PickWinner(ctx context.Context, campaignID, by uuid.UUID, variant string) error
- func (e *Engine) Prepare(ctx context.Context, campaignID uuid.UUID) error
- func (e *Engine) PumpSim(ctx context.Context, now time.Time) (int, *time.Time, error)
- func (e *Engine) ResolveInDoubt(ctx context.Context, campaignID, by uuid.UUID, resend bool, ...) (int64, error)
- func (e *Engine) Resume(ctx context.Context, campaignID, by uuid.UUID) error
- func (e *Engine) ResumeScope(ctx context.Context, campaignID, by uuid.UUID, in ResumeRequest) (ResumeResult, error)
- func (e *Engine) RetryRoute(ctx context.Context, campaignID, by, provider uuid.UUID) error
- func (e *Engine) Run(ctx context.Context, id uuid.UUID, budget time.Duration) (again time.Duration, done bool, err error)
- func (e *Engine) RunOutbox(ctx context.Context, budget time.Duration) (time.Duration, bool, error)
- func (e *Engine) SaveTrafficRules(ctx context.Context, ws, by uuid.UUID, in TrafficRulesInput) error
- func (e *Engine) SetRates(ctx context.Context, campaignID, by uuid.UUID, rates map[string]float64) error
- func (e *Engine) SetThresholds(ctx context.Context, campaignID, by uuid.UUID, ch ThresholdChange) error
- func (e *Engine) Snapshot(ctx context.Context, wsID, campaignID uuid.UUID) (LiveSnapshot, error)
- func (e *Engine) Start(ctx context.Context, campaignID, startedBy uuid.UUID) error
- func (e *Engine) StartWith(ctx context.Context, campaignID uuid.UUID, o StartOptions) error
- func (e *Engine) Step(ctx context.Context, rs *runState, now time.Time) (time.Duration, error)
- func (e *Engine) StopCanary(ctx context.Context, campaignID, by uuid.UUID) error
- func (e *Engine) Subscribe(ctx context.Context, ws, campaign uuid.UUID) (<-chan LiveSnapshot, func())
- func (e *Engine) TrafficRules(ctx context.Context, ws uuid.UUID, l i18n.Lang) (TrafficRules, error)
- func (e *Engine) Watch(ctx context.Context) error
- func (e *Engine) WatchComplaints(ctx context.Context) error
- type Estimate
- type EstimateAB
- type EstimateOptions
- type EstimateProvider
- type Excluded
- type InDoubtShare
- type IncidentCause
- type IncidentDetail
- type IncidentLogLine
- type IncidentOption
- type IncidentRate
- type LanguageVersions
- type LiveAB
- type LiveABVariant
- type LiveAcknowledgeRequest
- type LiveActionResult
- type LiveCanary
- type LiveCancelRequest
- type LiveCostByRoute
- type LiveDetails
- type LiveEvent
- type LiveExcluded
- type LiveFailover
- type LiveHeartbeat
- type LiveHelpers
- type LiveInDoubt
- type LiveInDoubtRequest
- type LiveIncident
- type LiveLimits
- type LiveMailbox
- type LiveMoveRequest
- type LiveOptions
- type LivePauseRequest
- type LivePostmaster
- type LiveProvider
- type LiveRatesRequest
- type LiveResumeRequest
- type LiveRetryRequest
- type LiveRouteShare
- type LiveShare
- type LiveSnapshot
- type LiveThreshold
- type LiveThresholdPart
- type LiveThresholdsRequest
- type LiveThrottle
- type LiveTotals
- type LiveWarmupHold
- type LiveWarmupTarget
- type LiveWatch
- type LiveWinnerRequest
- type MailboxClassifier
- type MoveCheck
- type MoveEstimate
- type OutboxArgs
- type OutboxWorker
- type Planner
- type PrepareArgs
- type PrepareWorker
- type RecipientLink
- type Rendered
- type ResumeChanges
- type ResumeRequest
- type ResumeResult
- type RunArgs
- type RunWorker
- type SeedChecker
- type SeedMailboxResult
- type SeedPlacement
- type SimArgs
- type SimWorker
- type StartArgs
- type StartOptions
- type StartWorker
- type StateError
- type StoreContent
- type Template
- type ThresholdChange
- type Thresholds
- type TrackedLink
- type Tracking
- type TrafficAction
- type TrafficReplyRule
- type TrafficRules
- type TrafficRulesInput
- type TrafficThresholds
- type TransactionalFailover
- type TransactionalFailure
- type TransactionalHooks
- type TransactionalOutbox
- type TransactionalOutboxArgs
- type TransactionalOutboxWorker
- type TransactionalOutcome
- type TransactionalWatchArgs
- type TransactionalWatchWorker
- type WatchArgs
- type WatchWorker
Constants ¶
const ( CanaryAuto = "auto" CanaryOn = "on" CanaryOff = "off" )
Canary choices (StartOptions.Canary, the send body's "canary"; C1).
const CapHoldReason = "warmup_cap"
CapHoldReason is a route's status detail reason while today's warm-up cap holds its share.
const DemoABWindow = 7 * time.Minute
DemoABWindow lets the A/B sample of a demo send finish before the winner goes to the rest (about 7 minutes for Weekly Digest #142).
const HoneypotVar = "rc_honeypot_url"
HoneypotVar is the Liquid variable holding the hidden link's URL.
const NoWinnerDefault = "default"
NoWinnerDefault is the only choice for a test without a clear winner: the default variant (A) goes to the rest (contract C14).
const OpenVar = varOpenURL
OpenVar is the Liquid variable holding the open pixel URL.
const TransactionalRetryWindow = 10 * time.Minute
TransactionalRetryWindow is how long a provider retries a transactional message after temporary errors before it goes to the route's fallback.
Variables ¶
var ( // ErrNotFound: no such campaign. ErrNotFound = errors.New("campaign not found") // ErrState: the campaign isn't in a state that allows the action. ErrState = errors.New("the campaign can't do that in its current state") )
Errors returned by the engine's actions.
var DefaultThresholds = Thresholds{Bounce: 2.0, Complaint: 0.1, MailboxComplaint: 0.1, Deferral: 40, APIErrors: 5.0, Scope: "route",
BlockBounce: 0.5, BlockAction: actPauseMailbox, UnknownWarn: 3, UnknownWarnAction: actWarn, UnknownPause: 5, UnknownPauseAction: actPauseSend,
DeferralSlow: 15, DeferralSlowWindow: 10, DeferralSlowAction: actSlow, DeferralWindow: 10, DeferralAction: actPauseMailbox, ComplaintAction: actPauseMailbox}
DefaultThresholds are used for limits a campaign doesn't set.
var DefaultThrottles = map[string]float64{"outlook": 5, "yahoo": 4, "icloud": 3}
DefaultThrottles are messages per second per mailbox provider when Send Readiness supplies none: Outlook, Yahoo and iCloud throttle new and bulk senders, Gmail and the rest take the provider's full rate.
var ErrRender = errors.New("the email's personalization doesn't render")
ErrRender wraps personalization errors in an email.
Functions ¶
func MaskAddress ¶
MaskAddress hides most of an address for the live feed: "ana.kowalski@gmail.com" → "a.k···@gmail.com".
func RegisterJobs ¶
RegisterJobs adds the sending workers and the watchdog.
func RegisterTraffic ¶
RegisterTraffic adds the Traffic rules screen's operations.
func RegisterTransactional ¶
func RegisterTransactional(reg *jobs.Registry, o *TransactionalOutbox)
RegisterTransactional adds the transactional outbox's workers.
func SeedMailboxOrder ¶
SeedMailboxOrder sorts mailbox provider keys as the monitor lists them.
Types ¶
type AutomationMailer ¶
type AutomationMailer struct{ E *Engine }
AutomationMailer is the automations engine's "Send email" step: it routes the contact on the Automations stream (automatic failover) and records the message inside the engine's transaction, and wakes the outbox once that transaction has committed.
func (AutomationMailer) QueueAutomationEmail ¶
func (m AutomationMailer) QueueAutomationEmail(ctx context.Context, tx pgx.Tx, o automations.OutgoingEmail) (automations.QueuedEmail, error)
QueueAutomationEmail implements automations.Mailer.
type CanaryGate ¶
type CanaryGate struct {
Key string `json:"key" enum:"bounce,block_bounce,deferral,complaint,seeds"`
Value *float64 `json:"value,omitempty"`
Limit float64 `json:"limit"`
Events int64 `json:"events"`
Base int64 `json:"base"`
// MinBase is the base a gate needs before it can fail.
MinBase int64 `json:"minBase"`
State string `json:"state" enum:"passing,failing,collecting"`
// Mailbox is the mailbox provider a per-mailbox-provider gate shows.
Mailbox string `json:"mailbox,omitempty"`
// Reported and NotReported are the mailbox providers whose complaints
// count, and the ones that don't report them (the complaint gate).
Reported []string `json:"reported,omitempty"`
NotReported []string `json:"notReported,omitempty"`
// Seeds is the seed placement (the seeds gate).
Seeds *SeedPlacement `json:"seeds,omitempty"`
}
CanaryGate is one gate's state.
type CanaryIP ¶
CanaryIP is a sending IP of a send's routes that never sent for the workspace, and the provider it belongs to (one type, so Review & send and the live monitor read the same API schema).
type CanaryPlan ¶
type CanaryPlan struct {
Auto bool `json:"auto"`
Reasons []string `json:"reasons"`
Size int64 `json:"size"`
// The workspace's canary settings, and the numbers behind the reasons.
Enabled bool `json:"enabled"`
Percent float64 `json:"percent"`
Seeds int `json:"seeds"`
WatchMinutes int `json:"watchMinutes"`
Audience int64 `json:"audience"`
// NeverMailed are the recipients that never got mail from the domain
// (before the audience is built: contacts added since its last send).
NeverMailed int64 `json:"neverMailed"`
Usual int64 `json:"usual"`
Domain string `json:"domain"`
// DomainSince is when the workspace first sent from the domain.
DomainSince *time.Time `json:"domainSince,omitempty"`
// NewIPs are the dedicated sending IPs of the send's routes that never
// sent for the workspace (review GS-10).
NewIPs []CanaryIP `json:"newIps"`
// MinAudience is the smallest audience an automatic canary runs on.
MinAudience int64 `json:"minAudience"`
}
CanaryPlan is what a send's canary would be (C1): whether it runs by itself, why, and how many recipients go first. Review & send shows it with the choice; the plan is worked out again when the send starts, on the audience as built.
type ComplaintWatchArgs ¶
type ComplaintWatchArgs struct{}
ComplaintWatchArgs runs the complaint watch of every send that has one.
func (ComplaintWatchArgs) InsertOpts ¶
func (ComplaintWatchArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
func (ComplaintWatchArgs) Kind ¶
func (ComplaintWatchArgs) Kind() string
Kind implements river.JobArgs.
type ComplaintWatchWorker ¶
type ComplaintWatchWorker struct {
river.WorkerDefaults[ComplaintWatchArgs]
E *Engine
}
ComplaintWatchWorker runs WatchComplaints.
func (*ComplaintWatchWorker) Work ¶
func (w *ComplaintWatchWorker) Work(ctx context.Context, _ *river.Job[ComplaintWatchArgs]) error
Work implements river.Worker.
type Conditional ¶
type Conditional interface {
// Plan reads a campaign's Visibility rules when its audience build
// starts; a nil Planner means the email has no conditional blocks.
Plan(ctx context.Context, workspaceID, campaignID uuid.UUID) (Planner, error)
// Links returns the per-recipient link variables of a campaign's polls
// and surveys, creating the polls of its content when a send starts.
Links(ctx context.Context, workspaceID, campaignID uuid.UUID) ([]RecipientLink, error)
// Cut removes the hidden blocks from compiled HTML and every marker.
Cut(html, hidden string) string
}
Conditional plugs conditional content and polls into a send (internal/visibility and internal/polls). Nil sends every block and leaves poll links empty.
type Content ¶
Content is what one email renders from: the subject, preheader, compiled HTML (MJML compiled by the composer, Liquid still inside) and plain text.
type DemoSendOptions ¶
type DemoSendOptions struct {
Workspace string
Campaign string
Scenario string
// Elapsed fast-forwards the send: it starts this long ago and the part
// it would have sent is sent at once on a virtual clock, with back-dated
// times, so the monitor opens mid-send.
Elapsed time.Duration
// ABWindow is the A/B test's window for the demo (the campaign's own
// window, hours, would hold the rest of the audience that long).
ABWindow time.Duration
// Reset clears an earlier send of the campaign first.
Reset bool
// Canary is the canary choice (auto, on, off); "" runs one in the
// normal scenario, as on the LiveMonitor and LiveMonitorCanary boards,
// and none in the others.
Canary string
}
DemoSendOptions start a demo send (development only).
type DemoSendResult ¶
type DemoSendResult struct {
CampaignID uuid.UUID
Name string
Recipients int64
Sent int64
Path string
}
DemoSendResult describes the started send.
type Engine ¶
type Engine struct {
Pool *pgxpool.Pool
Q *store.Queries
Audit *audit.Logger
Factory *manage.Factory
Links *linktoken.Signer
URLs publicurl.Builder
Jobs func() *jobs.Client
Log *slog.Logger
Now func() time.Time
// Readiness reruns Send Readiness at send time.
Readiness sending.Readiness
Segments sending.Segments
// Normalizer applies the demo transport's delivery events exactly as
// webhook events are applied.
Normalizer *ingest.Normalizer
// Recorder records the demo transport's opens and clicks through the
// same classification as real pixel fetches and clicks.
Recorder sending.Recorder
// Automations receives delivery outcomes of automation emails.
Automations *automations.Service
// Languages supplies the language versions each reader picks from;
// nil sends the source to everyone.
Languages LanguageVersions
// Conditional decides each reader's conditional blocks and fills in
// poll and survey links (conditional.go); nil sends every block.
Conditional Conditional
// QuietDemo makes the demo transport report no delivery or engagement
// events (throughput measurements of the send path alone).
QuietDemo bool
// SystemActor names the system that starts and completes a campaign
// no one pressed Send for, such as a recurring digest's issue ("System ·
// Engineering blog roundup, turned on by Sofia Rossi"). Nil, or a nil
// result, is plain "System".
SystemActor func(ctx context.Context, campaignID uuid.UUID) *audit.Actor
// Recipients add the variables blocks read per reader (Grow's
// referral.*, reward.* and recommendations.*); nil adds none.
Recipients func() []liquid.RecipientData
// Store refreshes store blocks with the products' prices and
// availability at send time, and fills automation emails' Checkout
// items (internal/commerce); nil sends them as written.
Store StoreContent
// Mailbox classifies company domains from their MX records before an
// audience is built, and automation recipients without a contact
// (internal/mailbox); nil keeps the providers contacts already carry.
Mailbox MailboxClassifier
// CallTimeout bounds one provider call (30 s when zero).
CallTimeout time.Duration
// StreamHeartbeat is how often the live stream says it's alive while
// nothing changes (15 s when zero; review GS-14).
StreamHeartbeat time.Duration
// Seeds sends a canary's copies to the workspace's seed mailboxes and
// reads where they landed (internal/placement; review GS-10); nil
// leaves the seed gate out.
Seeds SeedChecker
// contains filtered or unexported fields
}
Engine runs campaign sends and automation emails. It implements Starter.
func (*Engine) Acknowledge ¶
Acknowledge closes a notice a person has read: a complaint alert after the send, a threshold level that slowed the send down or warned, a reply rule's alert, the template's errors (bytype.go's isNotice).
func (*Engine) CanaryPlanFor ¶
CanaryPlanFor is a campaign's canary plan (C1): Review & send shows it and the choice.
func (*Engine) Cancel ¶
Cancel implements Starter: nothing more is sent. A scheduled campaign is taken back, as Review & send's Unschedule does: to approved when its approval still stands (it can be scheduled again as approved), otherwise to draft, and a hold ends. A running one is cancelled and what is left is marked not sent.
func (*Engine) CancelShare ¶
func (e *Engine) CancelShare(ctx context.Context, campaignID, by uuid.UUID, mailbox string, provider *uuid.UUID) (int64, error)
CancelShare skips what is left of a mailbox provider or a route; the rest of the campaign finishes normally.
func (*Engine) ContinueCanary ¶
ContinueCanary sends everyone now, before the watch ends or after a gate failed (people who can approve sends).
func (*Engine) DemoSend ¶
func (e *Engine) DemoSend(ctx context.Context, o DemoSendOptions) (DemoSendResult, error)
DemoSend starts a campaign's send through the demo transport as Sofia Rossi, with Marcus Chen's approval recorded (Oct 10 16:20 on the boards), so the live monitor's boards are reproduced with real moving data. It refuses unless every provider the Broadcasts route uses is a demo provider: it never sends real mail.
func (*Engine) Drive ¶
func (e *Engine) Drive(ctx context.Context, campaignID uuid.UUID, start time.Time, d time.Duration) (time.Time, bool, error)
Drive runs a send on a virtual clock from start for d, a step a second, applying the demo transport's events as they come due; idle stretches (retry back-off, the A/B window) are skipped up to the next due event. Tests and the demo command's fast-forward use it. It returns the virtual time it stopped at and whether the send ended (finished, paused or cancelled).
func (*Engine) DrivePrepare ¶
DrivePrepare builds the recipient list on a virtual clock (tests and the demo command).
func (*Engine) Estimate ¶
func (e *Engine) Estimate(ctx context.Context, campaignID uuid.UUID, o EstimateOptions) (Estimate, error)
Estimate plays a campaign's send out with the engine's rules.
func (*Engine) ExtendCanary ¶
ExtendCanary watches the canary 10 more minutes.
func (*Engine) HoldShares ¶
HoldShares implements sending.Outages: every running send's share on a provider the health job marked down goes through the send's outage path. A send whose loop is running right now is left to it: the loop rereads the provider within seconds and takes the same path.
func (*Engine) InDoubtHook ¶
func (e *Engine) InDoubtHook() ingest.MessageHook
InDoubtHook settles a message in doubt, or one left out while in doubt, when its provider reports an event for it: the provider took it after all. It counts as sent (rejected, when that is what the provider says; the event itself counts as usual before the hook); the in-doubt incident follows at the guard's next pass. Wired into the normalizer (internal/ingest).
func (*Engine) KickAutomationOutbox ¶
func (e *Engine) KickAutomationOutbox()
KickAutomationOutbox asks for a pass of the automation outbox for mail committed before the call (automation and milestone emails), as TransactionalOutbox.Kick does for transactional mail. Mail that a lost kick leaves is woken by the sending watch within 30 seconds.
func (*Engine) MoveShare ¶
MoveShare moves what is left of one provider's share to another (a person's decision during an outage, from the live monitor or the providers screen; it implements sending.ShareMover). The target is vetted as every move is; A/B and canary holdouts stay held on the new provider.
func (*Engine) OutboxStep ¶
OutboxStep sends one second's automation emails (tests and fast-forward).
func (*Engine) PickWinner ¶
PickWinner ends an A/B test with a person's choice.
func (*Engine) Prepare ¶
Prepare builds a campaign's recipient list: the audience's members minus suppressed, unsubscribed, bounced, complained and paused contacts and the exclusions, each routed to a provider with its A/B variant. A saved cursor lets it stop and run again without sending anyone twice. It holds the send's lock (errBusy when another process holds it).
func (*Engine) PumpSim ¶
PumpSim applies the demo transport's events that are due: delivery events through the same normalization as provider webhooks (event log, message status, counters, suppression list), opens and clicks through the tracking recorder (with its human-vs-machine classification). It returns how many it applied and when the next one is due.
func (*Engine) ResolveInDoubt ¶
func (e *Engine) ResolveInDoubt(ctx context.Context, campaignID, by uuid.UUID, resend bool, provider *uuid.UUID) (int64, error)
ResolveInDoubt is a person's decision on a campaign's messages in doubt: send them again (resend) or leave them out. It returns how many it changed.
func (*Engine) Resume ¶
Resume implements Starter: a paused campaign sends again, and every mailbox provider or route on hold is released. Every threshold that tripped re-arms from the current counts (review GS-2).
func (*Engine) ResumeScope ¶
func (e *Engine) ResumeScope(ctx context.Context, campaignID, by uuid.UUID, in ResumeRequest) (ResumeResult, error)
ResumeScope resumes a held mailbox provider or route, or the whole campaign, as is or with the recommended changes, optionally raising the limit that tripped. The resumed scope's thresholds re-arm from the current counts (review GS-2).
func (*Engine) RetryRoute ¶
RetryRoute keeps a held share on its provider and tests it (outages.go): one test message every minute, to a seed mailbox when the workspace has one; the share resumes by itself after three in a row go through, and a person is asked again if it still fails after 15 minutes.
func (*Engine) Run ¶
func (e *Engine) Run(ctx context.Context, id uuid.UUID, budget time.Duration) (again time.Duration, done bool, err error)
Run sends a campaign for up to budget, then returns how soon it should run again (done when there is nothing left to do now).
func (*Engine) RunOutbox ¶
RunOutbox sends queued automation emails per provider, within each provider's shared rate, for up to budget.
func (*Engine) SaveTrafficRules ¶
func (e *Engine) SaveTrafficRules(ctx context.Context, ws, by uuid.UUID, in TrafficRulesInput) error
SaveTrafficRules writes a workspace's traffic rules: the thresholds by type into its auto-pause defaults, the reply rules as listed (new ones added, missing ones removed), the canary and the watch; audited with what they were.
func (*Engine) SetRates ¶
func (e *Engine) SetRates(ctx context.Context, campaignID, by uuid.UUID, rates map[string]float64) error
SetRates changes a running or waiting send's rates per mailbox provider, audited with what they were.
func (*Engine) SetThresholds ¶
func (e *Engine) SetThresholds(ctx context.Context, campaignID, by uuid.UUID, ch ThresholdChange) error
SetThresholds changes a running or waiting send's thresholds, audited with what they were (review GS-2). The guard reads them again within seconds.
func (*Engine) Start ¶
Start implements Starter: it schedules the send when the campaign is set for a later time, and otherwise reruns Send Readiness and starts it. When the recheck turns Blocked nothing is sent and the error wraps sending.ErrNotReady; a scheduled send is also held (see hold).
func (*Engine) Step ¶
Step sends one second's worth across the campaign's routes and every two seconds checks thresholds, outages, the A/B test and completion. It returns how long nothing can be sent (0 when it sent or will send next second). now is explicit so tests and fast-forwarded demo sends drive it.
func (*Engine) StopCanary ¶
StopCanary stops the send: the recipients the canary held don't get it; the canary's results stay in the report.
func (*Engine) Subscribe ¶
func (e *Engine) Subscribe(ctx context.Context, ws, campaign uuid.UUID) (<-chan LiveSnapshot, func())
Subscribe streams a campaign's snapshots: the current one at once, then every change. cancel stops the stream.
func (*Engine) TrafficRules ¶
TrafficRules reads a workspace's traffic rules.
type Estimate ¶
type Estimate struct {
Start time.Time `json:"start"`
// End is when the last message goes out. Open is true when it isn't
// known: a person picks the A/B winner, so the rest waits for them.
End time.Time `json:"end"`
Open bool `json:"open,omitempty"`
// Providers are the routes, in the order of the recipients given.
Providers []EstimateProvider `json:"providers"`
// Throttles are the per-mailbox-provider throttles the send uses
// (messages per second; absent means the provider's full rate).
Throttles map[string]float64 `json:"throttles"`
// AB is the A/B test's timeline, nil without a test.
AB *EstimateAB `json:"ab,omitempty"`
// BestTime is true when each recipient gets it at their usual open
// hour, within 24 hours of the start.
BestTime bool `json:"bestTime,omitempty"`
// LocalTime is true when each recipient gets it at the same time of
// day in their own time zone: over about 26 hours from the start
// (review 2026-11 CA-5).
LocalTime bool `json:"localTime,omitempty"`
}
Estimate is how the engine would send a campaign.
type EstimateAB ¶
type EstimateAB struct {
Kind string `json:"kind"`
Variants int `json:"variants"`
TestPercent int `json:"testPercent"`
Sample int64 `json:"sample"`
// SampleEnd is when the sample's last message goes out; DecideAt when
// the winner is picked (nil when a person picks it).
SampleEnd time.Time `json:"sampleEnd"`
DecideAt *time.Time `json:"decideAt,omitempty"`
Hours int `json:"hours"`
}
EstimateAB is an A/B test's timeline: the sample goes first, the rest when the winner is picked.
type EstimateOptions ¶
type EstimateOptions struct {
// Start is when the send starts (now when zero).
Start time.Time
// Recipients counts the recipients per provider and mailbox provider.
Recipients map[uuid.UUID]map[string]int64
// Throttles are Send Readiness's per-mailbox-provider throttles for the
// send; nil keeps the workspace's and the defaults (sendThrottles).
Throttles map[string]float64
}
EstimateOptions describe the send an estimate is for. Send Readiness counts the recipients; the engine knows how it sends them.
type EstimateProvider ¶
type EstimateProvider struct {
ProviderID uuid.UUID `json:"providerId"`
Recipients int64 `json:"recipients"`
// Rate is the messages per second the engine sends at; RateFrom is
// where it comes from: published (the provider's own maximum),
// default (the adapter's, when the provider publishes none) or warmup
// (the warm-up plan's ramp).
Rate float64 `json:"rate"`
RateFrom string `json:"rateFrom" enum:"published,default,warmup"`
// Seconds is how long the route sends (waits left out); Done is when
// its last message goes out.
Seconds float64 `json:"seconds"`
Done time.Time `json:"done"`
// Days is how many days the warm-up plan's caps spread the share over
// (1: it all goes on the start day); CapLeft is what the plan allows
// on the start day (nil without a plan).
Days int `json:"days"`
CapLeft *int64 `json:"capLeft,omitempty"`
// QuotaLeft is the provider's 24-hour quota left (nil without one);
// OverQuota is how many messages wait for the quota to free up.
QuotaLeft *int64 `json:"quotaLeft,omitempty"`
OverQuota int64 `json:"overQuota,omitempty"`
// Held is true when the provider can't take mail now: its share waits
// (Send Readiness offers moving it).
Held bool `json:"held,omitempty"`
}
EstimateProvider is one route of the send.
type Excluded ¶
type Excluded struct {
Suppressed int64 `json:"suppressed"`
Unsubscribed int64 `json:"unsubscribed"`
Bounced int64 `json:"bounced"`
Complained int64 `json:"complained"`
Paused int64 `json:"paused"`
Role int64 `json:"role"`
Duplicates int64 `json:"duplicates"`
Sunset int64 `json:"sunset"`
Excluded int64 `json:"excluded"`
Tiers int64 `json:"tiers"`
// Capped counts contacts over the workspace's marketing cap (review
// 2026-11 AT-9).
Capped int64 `json:"capped"`
// Cadence counts readers whose chosen rhythm (weekly, monthly) this
// campaign doesn't reach (review 2026-11 CA-6).
Cadence int64 `json:"cadence"`
}
Excluded counts the contacts of the audience who don't receive the send.
type InDoubtShare ¶
type InDoubtShare struct {
// answer was lost).
Since time.Time `json:"since"`
// Idempotent: the provider recognizes a message it already took for
// WindowSeconds after the first try (its idempotency key).
// the end of the provider's window for the oldest of them, less a
// margin. Absent when the provider doesn't recognize them at all.
SafeUntil *time.Time `json:"safeUntil,omitempty"`
Safe bool `json:"safe"`
}
InDoubtShare is one sending provider's messages in doubt.
type IncidentCause ¶
IncidentCause is one likely cause: a bold lead and the evidence.
type IncidentDetail ¶
type IncidentDetail struct {
// Threshold trips: the scope's numbers when it tripped.
Sent int64 `json:"sent,omitempty"`
Total int64 `json:"total,omitempty"`
Delivered int64 `json:"delivered,omitempty"`
Events int64 `json:"events,omitempty"`
Base int64 `json:"base,omitempty"`
Campaign *IncidentRate `json:"campaign,omitempty"`
Secondary *IncidentRate `json:"secondary,omitempty"`
Note string `json:"note,omitempty"`
Continuing []string `json:"continuing,omitempty"`
Throttle float64 `json:"throttle,omitempty"`
// Action is what a level that didn't pause did (GS-11, GS-12):
// slowed (to SlowedTo messages per second), warned or alerted. Such an
// incident is a notice to acknowledge, not a decision. Window is a
// deferral level's window, or a burst's (Events and Base count within
// it), in minutes.
Action string `json:"action,omitempty" enum:"slowed,warned,alerted,"`
SlowedTo float64 `json:"slowedTo,omitempty"`
Window int `json:"window,omitempty"`
// Clear: the rate tripped clearly over its limit before the usual
// evidence (5 events and 500 sent or delivered), review R2.L7c.
Clear bool `json:"clear,omitempty"`
// Outages.
Reason string `json:"reason,omitempty"`
ErrorKind string `json:"errorKind,omitempty"`
From *time.Time `json:"from,omitempty"`
To *time.Time `json:"to,omitempty"`
Attempts int `json:"attempts,omitempty"`
Succeeded int `json:"succeeded"`
Host string `json:"host,omitempty"`
Policy string `json:"policy,omitempty"`
Log []IncidentLogLine `json:"log,omitempty"`
Probed bool `json:"probed,omitempty"`
// Retried: the share was retried for 15 minutes and still failed, so a
// person is asked again (outages.go).
Retried bool `json:"retried,omitempty"`
ErrorRate float64 `json:"errorRate,omitempty"`
SentOnRoute int64 `json:"sentOnRoute,omitempty"`
Remaining int64 `json:"remaining,omitempty"`
Move *MoveEstimate `json:"move,omitempty"`
WarmupNote string `json:"warmupNote,omitempty"`
// Messages in doubt (doubt.go), per sending provider.
InDoubt []InDoubtShare `json:"inDoubt,omitempty"`
Causes []IncidentCause `json:"causes,omitempty"`
Recommendations []string `json:"recommendations,omitempty"`
Options []IncidentOption `json:"options,omitempty"`
Changes *ResumeChanges `json:"changes,omitempty"`
// contains filtered or unexported fields
}
IncidentDetail is what the engine stores with an incident (campaign_incidents.detail): the evidence at the moment it tripped, likely causes, recommendations and the choices offered.
func (IncidentDetail) In ¶
func (d IncidentDetail) In(l i18n.Lang) IncidentDetail
In is the detail in a reader's language: kept sentences in their messages, the rest as stored.
type IncidentLogLine ¶
type IncidentOption ¶
type IncidentOption struct {
Key string `json:"key"`
Title string `json:"title"`
Body string `json:"body"`
Recommended bool `json:"recommended"`
// Action is the primary button's label when this option is chosen.
Action string `json:"action"`
}
IncidentOption is one way to continue.
type IncidentRate ¶
type IncidentRate struct {
Metric string `json:"metric"`
Events int64 `json:"events"`
Base int64 `json:"base"`
Value float64 `json:"value"`
Limit float64 `json:"limit"`
}
IncidentRate is a rate against its limit.
type LanguageVersions ¶
type LanguageVersions interface {
CampaignSendSet(ctx context.Context, workspaceID, campaignID uuid.UUID) (languages.SendSet, error)
AutomationSendSet(ctx context.Context, workspaceID, emailID uuid.UUID, version int) (languages.SendSet, error)
}
LanguageVersions supplies an email's language versions when a send starts (internal/languages).
type LiveAB ¶
type LiveAB struct {
Kind string `json:"kind"`
Metric string `json:"metric"`
Phase string `json:"phase" enum:"testing,decided"`
Sample int `json:"sample"`
Variants []LiveABVariant `json:"variants"`
Leader string `json:"leader"`
DecideAt *time.Time `json:"decideAt,omitempty"`
Winner string `json:"winner"`
}
LiveAB is the A/B test's progress.
type LiveABVariant ¶
type LiveABVariant struct {
Key string `json:"key"`
Rate float64 `json:"rate"`
Sent int64 `json:"sent"`
}
LiveABVariant is one variant's result so far.
type LiveAcknowledgeRequest ¶
type LiveAcknowledgeRequest struct {
IncidentID string `json:"incidentId" format:"uuid"`
}
LiveAcknowledgeRequest marks an alert as read (complaints after the send).
type LiveActionResult ¶
type LiveActionResult struct {
Moved int64 `json:"moved"`
Cancelled int64 `json:"cancelled"`
Excluded int64 `json:"excluded"`
// Decided is how many messages in doubt were sent again or left out.
Decided int64 `json:"decided"`
Snapshot LiveSnapshot `json:"snapshot"`
}
LiveActionResult is what an action changed, with the new snapshot.
type LiveCanary ¶
type LiveCanary struct {
Phase string `json:"phase" enum:"sending,watching,held,passed,continued,stopped"`
// Chosen: a person asked for it in Review & send; otherwise Reasons
// say why Traffic rules ran it (new_domain, new_ip, never_mailed,
// over_usual).
Chosen bool `json:"chosen"`
Reasons []string `json:"reasons"`
// NewIPs are the sending IPs that never sent for the workspace before
// (the new_ip reason).
NewIPs []CanaryIP `json:"newIps"`
Percent float64 `json:"percent"`
// Size is the canary's recipients; Sent how many went; Seeds the seed
// inboxes that got it too.
Size int64 `json:"size"`
Sent int64 `json:"sent"`
Seeds int `json:"seeds"`
// Queued are the recipients waiting for it to pass.
Queued int64 `json:"queued"`
NeverMailed int64 `json:"neverMailed"`
Usual int64 `json:"usual"`
Domain string `json:"domain"`
// StartedAt is when the canary started, SentAt when its last message
// went, Until when the watch ends (the main send starts by itself then).
StartedAt *time.Time `json:"startedAt,omitempty"`
SentAt *time.Time `json:"sentAt,omitempty"`
Until *time.Time `json:"until,omitempty"`
// WatchMinutes is the watch's length, Extended the minutes people added.
WatchMinutes int `json:"watchMinutes"`
Extended int `json:"extended"`
DecidedAt *time.Time `json:"decidedAt,omitempty"`
DecidedBy string `json:"decidedBy,omitempty"`
Gates []CanaryGate `json:"gates"`
// Seeds' placement, per mailbox provider (nil until a copy is found).
Placement *SeedPlacement `json:"placement,omitempty"`
// MainSeconds is how long the main send takes once it starts, at the
// routes' and mailbox providers' rates (the monitor's "everyone has it
// by about").
MainSeconds int64 `json:"mainSeconds"`
}
LiveCanary is the canary on the live monitor (LiveMonitorCanary; review GS-10): why it runs, how far it is, its gates and its seed placement.
type LiveCancelRequest ¶
type LiveCancelRequest struct {
Mailbox string `json:"mailbox,omitempty" enum:"gmail,outlook,yahoo,icloud,other"`
ProviderID string `json:"providerId,omitempty" format:"uuid"`
}
LiveCancelRequest cancels the whole send, or one share of it.
type LiveCostByRoute ¶
LiveCostByRoute is the cost so far and planned.
type LiveDetails ¶
type LiveDetails struct {
From string `json:"from"`
Audience string `json:"audience"`
AudienceCount int64 `json:"audienceCount"`
Route string `json:"route"`
Cost float64 `json:"cost"`
CostPlanned float64 `json:"costPlanned"`
ScheduledBy string `json:"scheduledBy"`
// WatchHours is how long complaints are watched after the send
// (Traffic rules; 0: not watched).
WatchHours int `json:"watchHours"`
}
LiveDetails is the "Send details" card.
type LiveEvent ¶
type LiveEvent struct {
ID string `json:"id"`
At time.Time `json:"at"`
Kind string `json:"kind"`
Label string `json:"label"`
Short string `json:"short"`
Tone string `json:"tone" enum:"ok,warn,bad,info,neutral"`
Address string `json:"address"`
Detail string `json:"detail"`
// contains filtered or unexported fields
}
LiveEvent is one line of the live event feed. Addresses are masked.
type LiveExcluded ¶
type LiveExcluded struct {
Suppressed int64 `json:"suppressed"`
Unsubscribed int64 `json:"unsubscribed"`
Bounced int64 `json:"bounced"`
Complained int64 `json:"complained"`
Paused int64 `json:"paused"`
Role int64 `json:"role"`
// Duplicates are aliases of another contact of the audience (the same mailbox).
Duplicates int64 `json:"duplicates"`
Sunset int64 `json:"sunset"`
Excluded int64 `json:"excluded"`
Tiers int64 `json:"tiers"`
}
LiveExcluded counts who the audience build left out.
type LiveFailover ¶
LiveFailover is another stream that moved off a provider on its own.
type LiveHeartbeat ¶
LiveHeartbeat is the stream's sign of life while nothing changes (review GS-14: stale data detection).
type LiveHelpers ¶
type LiveHelpers struct {
Pause []string `json:"pause"`
Send []string `json:"send"`
// Approve can continue a canary early (review GS-10).
Approve []string `json:"approve"`
}
LiveHelpers are up to two members who hold each action's permission.
type LiveInDoubt ¶
type LiveInDoubt struct {
Count int64 `json:"count"`
Since time.Time `json:"since"`
Providers []InDoubtShare `json:"providers"`
// Safe: every provider involved still recognizes the messages it took
// (inside its idempotency window), so sending them again now can't
// deliver anything twice.
Safe bool `json:"safe"`
// Waiting: nothing else is left to send, so the send waits for this
// decision (resuming can't send anything; the decision is what goes
// on).
Waiting bool `json:"waiting"`
// IncidentID is the open in-doubt incident with the ways to continue.
IncidentID string `json:"incidentId,omitempty"`
}
LiveInDoubt is what is in doubt, per sending provider.
type LiveInDoubtRequest ¶
type LiveInDoubtRequest struct {
Action string `json:"action" enum:"resend,leave_out"`
ProviderID string `json:"providerId,omitempty" format:"uuid"`
}
LiveInDoubtRequest decides on the messages in doubt: send them again or leave them out, all of them or one sending provider's.
type LiveIncident ¶
type LiveIncident struct {
ID string `json:"id"`
Kind string `` /* 126-byte string literal not displayed */
Scope string `json:"scope" enum:"campaign,route,mailbox_provider"`
Mailbox string `json:"mailbox"`
MailboxName string `json:"mailboxName"`
ProviderID string `json:"providerId"`
Provider string `json:"provider"`
ProviderShort string `json:"providerShort"`
Metric string `json:"metric"`
Value *float64 `json:"value,omitempty"`
Limit *float64 `json:"limit,omitempty"`
Held int64 `json:"held"`
TrippedAt time.Time `json:"trippedAt"`
ResolvedAt *time.Time `json:"resolvedAt,omitempty"`
Resolution string `json:"resolution"`
Detail IncidentDetail `json:"detail"`
// Since is the tripped scope's rate on what was delivered (or sent)
// after the trip, for the resume dialog (review GS-2).
Since *IncidentRate `json:"since,omitempty"`
}
LiveIncident is an auto-pause, outage or blocked recheck.
func (LiveIncident) In ¶
func (in LiveIncident) In(l i18n.Lang) LiveIncident
In is an incident in a reader's language.
type LiveLimits ¶
type LiveLimits struct {
Bounce float64 `json:"bounce"`
Complaint float64 `json:"complaint"`
MailboxComplaint float64 `json:"mailboxComplaint"`
Deferral float64 `json:"deferral"`
APIErrors float64 `json:"apiErrors"`
}
LiveLimits are a send's auto-pause thresholds, in percent.
type LiveMailbox ¶
type LiveMailbox struct {
Key string `json:"key" enum:"gmail,outlook,yahoo,icloud,other"`
Name string `json:"name"`
Sent int64 `json:"sent"`
Remaining int64 `json:"remaining"`
Delivered int64 `json:"delivered"`
Bounced int64 `json:"bounced"`
Complained int64 `json:"complained"`
Opened int64 `json:"opened"`
DeliveredRate *float64 `json:"deliveredRate,omitempty"`
BounceRate *float64 `json:"bounceRate,omitempty"`
ComplaintRate *float64 `json:"complaintRate,omitempty"`
// ComplaintReason says why ComplaintRate is null: Gmail and iCloud
// don't report complaints per message (review F-2).
ComplaintReason string `json:"complaintReason,omitempty" enum:"not_reported"`
OpenRate *float64 `json:"openRate,omitempty"`
// DeferredRate is the share of what went to it within the deferral
// window that it asked to retry (review GS-14), in percent.
DeferredRate *float64 `json:"deferredRate,omitempty"`
// Deferred are its messages deferred once or more; Retrying those still
// being retried (the canary's table; review GS-14).
Deferred int64 `json:"deferred"`
Retrying int64 `json:"retrying"`
Throttle *float64 `json:"throttle,omitempty" doc:"Messages per second; absent = the provider's full rate"`
// DoneAt is when its mail still to send has gone, at current rates
// with its limit (review GS-8); absent while it waits.
DoneAt *time.Time `json:"doneAt,omitempty"`
Held bool `json:"held"`
HeldSince *time.Time `json:"heldSince,omitempty"`
// HeldUntil is when a timed hold ends by itself (a reply rule's).
HeldUntil *time.Time `json:"heldUntil,omitempty"`
Status string `json:"status" enum:"ok,sending,paused,done"`
}
LiveMailbox is one mailbox provider's row.
type LiveMoveRequest ¶
type LiveMoveRequest struct {
FromProviderID string `json:"fromProviderId" format:"uuid"`
ToProviderID string `json:"toProviderId" format:"uuid"`
}
LiveMoveRequest moves a held share to another sending provider.
type LiveOptions ¶
type LiveOptions struct {
// CanResume: there is something to resume (paused or held).
CanResume bool `json:"canResume"`
CanPause bool `json:"canPause"`
CanCancel bool `json:"canCancel"`
}
LiveOptions are flags the screen needs.
type LivePauseRequest ¶
type LivePauseRequest struct {
Reason string `json:"reason,omitempty" maxLength:"500"`
}
LivePauseRequest pauses a running send.
type LivePostmaster ¶
type LivePostmaster struct {
// SpamRate is in percent.
SpamRate float64 `json:"spamRate"`
Day string `json:"day" format:"date"`
}
LivePostmaster is Gmail's latest daily spam rate for the sending domain (Postmaster Tools): Gmail reports a rate per day, not single complaints.
type LiveProvider ¶
type LiveProvider struct {
ID string `json:"id"`
Name string `json:"name"`
Short string `json:"short"`
Adapter string `json:"adapter"`
Color string `json:"color" enum:"ses,postal,postmark,other"`
Sent int64 `json:"sent"`
Planned int64 `json:"planned"`
Remaining int64 `json:"remaining"`
Rate float64 `json:"rate"`
DeliveredRate *float64 `json:"deliveredRate,omitempty"`
BounceRate *float64 `json:"bounceRate,omitempty"`
ComplaintRate *float64 `json:"complaintRate,omitempty"`
APIErrorRate *float64 `json:"apiErrorRate,omitempty"`
Status string `json:"status"`
RouteStatus string `json:"routeStatus" enum:"pending,sending,held,paused,done,cancelled"`
DownSince *time.Time `json:"downSince,omitempty"`
Host string `json:"host"`
IP string `json:"ip"`
QuotaFree *int64 `json:"quotaFree,omitempty"`
QuotaMax *int64 `json:"quotaMax,omitempty"`
WarmupDay *int `json:"warmupDay,omitempty"`
WarmupDays *int `json:"warmupDays,omitempty"`
WarmupCap *int64 `json:"warmupCap,omitempty"`
WarmupSent *int64 `json:"warmupSent,omitempty"`
// WarmupHold is set while today's warm-up cap (or a paused plan) holds
// the route's share (review PR-8).
WarmupHold *LiveWarmupHold `json:"warmupHold,omitempty"`
Cost float64 `json:"cost"`
PlannedCost float64 `json:"plannedCost"`
Retrying bool `json:"retrying"`
RetryUntil *time.Time `json:"retryUntil,omitempty"`
// Probing: the share is held for an outage nobody decided on yet and
// tests its provider on its own (review GS-3); a person's decision
// still wins.
Probing bool `json:"probing"`
// While a share is retried or probing: the test messages that went
// through in a row (it resumes at ProbesNeeded), when the next one goes
// and whether they go to a seed mailbox.
Probes int `json:"probes"`
ProbesNeeded int `json:"probesNeeded"`
NextProbe *time.Time `json:"nextProbe,omitempty"`
ProbeSeed bool `json:"probeSeed"`
// InfersDelivery: the provider reports no deliveries (plain SMTP), so
// its delivered count is inferred from the server's acceptance (review
// GS-7: "delivered (inferred)").
InfersDelivery bool `json:"infersDelivery"`
// Idempotent: the provider recognizes a message it already took, so a
// retry after a lost answer never delivers it twice (review GS-1), for
// IdempotencySeconds after the first try.
Idempotent bool `json:"idempotent"`
IdempotencySeconds int64 `json:"idempotencySeconds,omitempty"`
// DoneAt is when its share is done at current rates, including the
// per-mailbox limits (review GS-8: "Done about"); absent while it
// waits.
DoneAt *time.Time `json:"doneAt,omitempty"`
}
LiveProvider is one sending provider's row.
type LiveRatesRequest ¶
type LiveRatesRequest struct {
// Rates in messages per second by mailbox provider (gmail, outlook,
// yahoo, icloud, other); 0 is the sending providers' full rate. A
// mailbox provider left out keeps its rate.
Rates map[string]float64 `json:"rates" minProperties:"1" maxProperties:"5"`
}
LiveRatesRequest changes a running or waiting send's rates per mailbox provider for the rest of the send, on every route (review GS-13).
type LiveResumeRequest ¶
type LiveResumeRequest struct {
Mailbox string `json:"mailbox,omitempty" enum:"gmail,outlook,yahoo,icloud,other"`
ProviderID string `json:"providerId,omitempty" format:"uuid"`
// WithChanges applies the incident's recommended changes (exclude the
// group, lower the rate, hand the excluded contacts to the flow).
WithChanges bool `json:"withChanges,omitempty"`
// Limit raises the limit of the metric that tripped, for this send
// only, in percent ("Resume with the threshold raised to 0.20%").
Limit *float64 `json:"limit,omitempty" minimum:"0.01" maximum:"100"`
// Rate slows the resumed mailbox provider or route down for the rest
// of the send, in messages per second ("Resume at 2 /s").
Rate *float64 `json:"rate,omitempty" minimum:"0.1" maximum:"10000"`
}
LiveResumeRequest resumes a paused send, or one mailbox provider or sending provider on hold.
type LiveRetryRequest ¶
type LiveRetryRequest struct {
ProviderID string `json:"providerId" format:"uuid"`
}
LiveRetryRequest retries a held share on its provider.
type LiveRouteShare ¶
type LiveRouteShare struct {
}
LiveRouteShare is a provider's planned share (the route line).
type LiveSnapshot ¶
type LiveSnapshot struct {
CampaignID string `json:"campaignId"`
Name string `json:"name"`
Status string `json:"status" enum:"draft,approval,approved,scheduled,sending,paused,sent,cancelled,failed"`
// State is what the monitor shows: idle (not started), scheduled,
// preparing (building the queue), sending, partial (a mailbox provider
// or route on hold while the rest sends), paused, finished, cancelled
// or failed.
State string `json:"state" enum:"idle,scheduled,preparing,sending,partial,paused,finished,cancelled,failed"`
At time.Time `json:"at"`
Version int64 `json:"version" doc:"Milliseconds since the epoch; the SSE event id"`
StartedAt *time.Time `json:"startedAt,omitempty"`
ScheduledAt *time.Time `json:"scheduledAt,omitempty"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
PreparedAt *time.Time `json:"preparedAt,omitempty"`
StartedBy string `json:"startedBy"`
ApprovedBy string `json:"approvedBy"`
ApprovedAt *time.Time `json:"approvedAt,omitempty"`
ScheduledBy string `json:"scheduledBy"`
PausedBy string `json:"pausedBy"`
PausedAt *time.Time `json:"pausedAt,omitempty"`
PauseReason string `json:"pauseReason"`
// Recipients is the audience after exclusions.
Recipients int64 `json:"recipients"`
Sent int64 `json:"sent"`
// Queued is still to send now; Held waits for a decision (a mailbox
// provider or route on hold); Waiting waits for the A/B winner; Unsent
// will never be sent (cancelled, rejected, failed).
Queued int64 `json:"queued"`
Held int64 `json:"held"`
Waiting int64 `json:"waiting"`
// Retrying are the messages a mailbox provider deferred that the
// sending provider is still retrying (review GS-14).
Retrying int64 `json:"retrying"`
Unsent int64 `json:"unsent"`
Percent float64 `json:"percent"`
Rate float64 `json:"rate" doc:"Messages per second now"`
ETASeconds *int64 `json:"etaSeconds,omitempty"`
FinishesAt *time.Time `json:"finishesAt,omitempty"`
Totals LiveTotals `json:"totals"`
Mailboxes []LiveMailbox `json:"mailboxes"`
Providers []LiveProvider `json:"providers"`
Thresholds []LiveThreshold `json:"thresholds"`
ThresholdScope string `json:"thresholdScope" enum:"route,campaign"`
// Limits are the send's thresholds, as "Edit for this send" changes
// them (review GS-2).
Limits LiveLimits `json:"limits"`
// Watch is the complaint watch after the send (review GS-6).
Watch *LiveWatch `json:"watch,omitempty"`
// DeferralWindow is the minutes the mailbox providers' deferral rates
// count (the first deferral level's window; 0: none).
DeferralWindow int `json:"deferralWindow,omitempty"`
// Canary is the send's canary (review GS-10), when it has one.
Canary *LiveCanary `json:"canary,omitempty"`
// Postmaster is Gmail's latest daily spam rate for the sending domain.
Postmaster *LivePostmaster `json:"postmaster,omitempty"`
Details LiveDetails `json:"details"`
DeliveredMix []LiveShare `json:"deliveredMix"`
AB *LiveAB `json:"ab,omitempty"`
Incident *LiveIncident `json:"incident,omitempty"`
Incidents []LiveIncident `json:"incidents"`
Events []LiveEvent `json:"events"`
EventsVia string `json:"eventsVia"`
LastEventAt *time.Time `json:"lastEventAt,omitempty"`
Failovers []LiveFailover `json:"failovers"`
// SharedStreams are the other streams (Automations, System) that route
// to a sending provider whose share is held.
Excluded LiveExcluded `json:"excluded"`
Error string `json:"error"`
Resumed bool `json:"resumed"`
Duration *int64 `json:"durationSeconds,omitempty"`
Cost LiveCostByRoute `json:"cost"`
ProvidersHeld []string `json:"providersHeld"`
MailboxesHeld []string `json:"mailboxesHeld"`
Continuing []string `json:"continuing"`
PauseScopeHint string `json:"pauseScopeHint"`
Throttles []LiveThrottle `json:"throttles"`
Options LiveOptions `json:"options"`
Routes []LiveRouteShare `json:"routes"`
// InDoubt are the messages nobody knows whether their provider took
// (review GS-1): they wait for a person, never sent again on a guess.
InDoubt *LiveInDoubt `json:"inDoubt,omitempty"`
// Helpers names who can pause and who can resume, for the reason on a
// disabled button. Only the GET fills it; the stream leaves it out.
Helpers *LiveHelpers `json:"helpers,omitempty"`
// contains filtered or unexported fields
}
LiveSnapshot is the live monitor's view of a send (spec 7.6): progress and ETA, counts, the per-mailbox-provider and per-sending-provider breakdowns, thresholds against their limits, the open incident and the newest events.
func (LiveSnapshot) In ¶
func (s LiveSnapshot) In(l i18n.Lang) LiveSnapshot
In is the snapshot in a reader's language: what the engine writes in words, with names and the providers' own words as they are. English readers read it as built.
type LiveThreshold ¶
type LiveThreshold struct {
Key string `json:"key" enum:"bounce,block_bounce,deferral,complaint,mailbox_complaint,reply_rules,api_errors"`
Value *float64 `json:"value,omitempty"`
Limit float64 `json:"limit"`
// Mailbox is the mailbox provider a per-mailbox-provider row shows (the
// one closest to its limit).
Mailbox string `json:"mailbox,omitempty"`
Events int64 `json:"events"`
Base int64 `json:"base"`
MinEvents int64 `json:"minEvents"`
MinBase int64 `json:"minBase"`
// AnyVolume: below MinEvents and MinBase the rate still trips once it
// is clearly over its limit, from 3 events (complaints and block/policy
// bounces, review R2.L7c).
AnyVolume bool `json:"anyVolume"`
// State: ok (watching), near (at 90% of the limit or more), collecting
// (at or near the limit without the evidence to trip yet), tripped, na
// (nothing to count: see Reason).
State string `json:"state" enum:"ok,near,collecting,tripped,na"`
Reason string `json:"reason,omitempty" enum:"no_data,not_reported"`
// Window is the minutes a windowed rate counts (deferrals); Action what
// the threshold does at its limit (pause_mailbox, slow, pause_send,
// warn).
Window int `json:"window,omitempty"`
Action string `json:"action,omitempty"`
// Duration is how long a reply rule's action lasts, in minutes (0:
// until someone resumes).
Duration int `json:"duration,omitempty"`
// Parts break the row down: the API error rate per sending provider,
// the mailbox providers a whole-send complaint rate counts.
Parts []LiveThresholdPart `json:"parts,omitempty"`
}
LiveThreshold is a rate against its auto-pause limit, with the evidence behind it (review GS-6): the events and the base it counts, and what the guard needs before it can trip. Without data the value is null with a reason (F-3).
type LiveThresholdPart ¶
type LiveThresholdPart struct {
Name string `json:"name"`
Key string `json:"key,omitempty"`
Value *float64 `json:"value,omitempty"`
}
LiveThresholdPart is one part of a threshold's row.
type LiveThresholdsRequest ¶
type LiveThresholdsRequest struct {
Bounce *float64 `json:"bounce,omitempty" minimum:"0.1" maximum:"20"`
Complaint *float64 `json:"complaint,omitempty" minimum:"0.01" maximum:"5"`
MailboxComplaint *float64 `json:"mailboxComplaint,omitempty" minimum:"0.01" maximum:"5"`
Deferral *float64 `json:"deferral,omitempty" minimum:"1" maximum:"100"`
APIErrors *float64 `json:"apiErrors,omitempty" minimum:"1" maximum:"100"`
// Scope: pause only the affected route or mailbox provider, or the whole campaign.
Scope string `json:"scope,omitempty" enum:"route,campaign"`
}
LiveThresholdsRequest changes a running or waiting send's auto-pause thresholds, in percent; a field left out keeps its value.
type LiveThrottle ¶
LiveThrottle is a mailbox provider's rate limit in this send.
type LiveTotals ¶
type LiveTotals struct {
Delivered int64 `json:"delivered"`
Bounced int64 `json:"bounced"`
HardBounced int64 `json:"hardBounced"`
SoftBounced int64 `json:"softBounced"`
// BlockBounced and UnknownBounced split the hard bounces: block/policy
// rejections, and unknown users with the rest (review GS-11).
BlockBounced int64 `json:"blockBounced"`
UnknownBounced int64 `json:"unknownBounced"`
Complained int64 `json:"complained"`
Deferred int64 `json:"deferred"`
Rejected int64 `json:"rejected"`
Opened int64 `json:"opened"`
OpenedHuman int64 `json:"openedHuman"`
OpenedMachine int64 `json:"openedMachine"`
Clicked int64 `json:"clicked"`
Unsubscribed int64 `json:"unsubscribed"`
// ComplaintBase is what was delivered where mailbox providers report
// complaints: the complaint rate's base (review F-2).
ComplaintBase int64 `json:"complaintBase"`
// NotReported names the mailbox providers this send reached that
// don't report complaints ("Gmail", "iCloud").
NotReported []string `json:"notReported"`
}
LiveTotals are the campaign's counts.
type LiveWarmupHold ¶
type LiveWarmupHold struct {
PlanID string `json:"planId"`
// Held is how many recipients wait.
Held int64 `json:"held"`
// Since is when the cap stopped the share.
Since *time.Time `json:"since,omitempty"`
// Until is when tomorrow's cap starts and the share goes on; absent
// while a paused plan holds it (Paused).
Until *time.Time `json:"until,omitempty"`
Paused bool `json:"paused"`
// Decision is "wait" once someone chose to wait for the cap.
Decision string `json:"decision,omitempty" enum:"wait"`
// Cap is today's cap.
Cap int64 `json:"cap"`
// Targets are the providers the share could move to, vetted as a move
// is (state.Vet); those that can take it come first.
Targets []LiveWarmupTarget `json:"targets"`
}
LiveWarmupHold is a route's share that today's warm-up cap (or a paused plan) holds (review PR-8, warmup_send.go). It goes on by itself with tomorrow's cap, or once the plan resumes, unless someone moves it to a warm provider or cancels the rest (POST warmup/{planId}/held/{campaignId}: waiting and moving need campaigns:send, cancelling campaigns:pause).
func (*LiveWarmupHold) In ¶
func (h *LiveWarmupHold) In(l i18n.Lang) *LiveWarmupHold
In is the hold in a reader's language: why a provider can't take it.
type LiveWarmupTarget ¶
type LiveWarmupTarget struct {
ProviderID string `json:"providerId"`
Name string `json:"name"`
Short string `json:"short"`
Allowed bool `json:"allowed"`
// Reason is why it can't take the share: its first failed check.
Reason string `json:"reason,omitempty"`
// contains filtered or unexported fields
}
LiveWarmupTarget is a provider a held share could move to.
type LiveWatch ¶
type LiveWatch struct {
Until time.Time `json:"until"`
Hours int `json:"hours"`
Active bool `json:"active"`
Alert bool `json:"alert"`
// Limit is the complaint limit per mailbox provider.
Limit float64 `json:"limit"`
Rows []LiveThreshold `json:"rows"`
}
LiveWatch is the complaint watch after a send (LiveMonitorStates' complete state, review GS-6): until when, whether people are alerted, and each mailbox provider that reports complaints against its limit.
type LiveWinnerRequest ¶
type LiveWinnerRequest struct {
Variant string `json:"variant" enum:"A,B,C"`
}
LiveWinnerRequest picks the A/B winner.
type MailboxClassifier ¶
type MailboxClassifier interface {
ClassifyPending(ctx context.Context, workspaceID uuid.UUID, budget time.Duration) (int64, error)
ForEmail(ctx context.Context, email string) mailbox.Class
}
MailboxClassifier is the part of mailbox.Classifier the engine uses.
type MoveCheck ¶
type MoveCheck struct {
Key string `json:"key"`
Result string `json:"result" enum:"pass,warn,unknown"`
Text string `json:"text"`
}
MoveCheck is one check a move's target passed ("pass") or that couldn't be told ("unknown"), as a sentence.
type MoveEstimate ¶
type MoveEstimate struct {
TargetID string `json:"targetId"`
Target string `json:"target"`
TargetShort string `json:"targetShort"`
ExtraCost float64 `json:"extraCost"`
ExtraSeconds int64 `json:"extraSeconds"`
// Rate is the target's rate in messages per second ("Extra time at 14 /s").
Rate float64 `json:"rate"`
QuotaFree *int64 `json:"quotaFree,omitempty"`
QuotaMax *int64 `json:"quotaMax,omitempty"`
Risk string `json:"risk"` // low, high
RiskText string `json:"riskText"`
// Checks are what ReputeCast checked on the target before offering
// it (review GS-5): the sender's domain, its quota, its warm-up, and
// what happens to the recipients held for the A/B test or the canary.
Checks []MoveCheck `json:"checks,omitempty"`
}
MoveEstimate is what moving a held share to another provider costs.
type OutboxArgs ¶
type OutboxArgs struct{}
OutboxArgs sends queued automation emails.
func (OutboxArgs) InsertOpts ¶
func (OutboxArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
type OutboxWorker ¶
type OutboxWorker struct {
river.WorkerDefaults[OutboxArgs]
E *Engine
}
func (*OutboxWorker) NextRetry ¶
func (w *OutboxWorker) NextRetry(job *river.Job[OutboxArgs]) time.Time
NextRetry implements river.Worker.
func (*OutboxWorker) Timeout ¶
func (w *OutboxWorker) Timeout(*river.Job[OutboxArgs]) time.Duration
func (*OutboxWorker) Work ¶
func (w *OutboxWorker) Work(ctx context.Context, _ *river.Job[OutboxArgs]) error
Work implements river.Worker.
type Planner ¶
type Planner interface {
Hidden(ctx context.Context, contacts []uuid.UUID) (map[uuid.UUID]string, error)
}
Planner decides the hidden blocks of a page of recipients.
type PrepareArgs ¶
PrepareArgs builds a campaign's recipient list.
func (PrepareArgs) InsertOpts ¶
func (PrepareArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
type PrepareWorker ¶
type PrepareWorker struct {
river.WorkerDefaults[PrepareArgs]
E *Engine
}
func (*PrepareWorker) NextRetry ¶
func (w *PrepareWorker) NextRetry(job *river.Job[PrepareArgs]) time.Time
NextRetry implements river.Worker.
func (*PrepareWorker) Timeout ¶
func (w *PrepareWorker) Timeout(*river.Job[PrepareArgs]) time.Duration
Timeout allows a large audience build.
func (*PrepareWorker) Work ¶
func (w *PrepareWorker) Work(ctx context.Context, job *river.Job[PrepareArgs]) error
Work implements river.Worker. While another process holds the send (the demo command's fast-forward), it comes back a little later.
type RecipientLink ¶
type RecipientLink struct {
Var string
// URL builds the recipient's link from the message and contact ids.
URL func(messageID, contactID uuid.UUID) string
}
RecipientLink is a Liquid variable filled in per recipient: a poll's answer link base ({{ rc_poll_a1b2c3 }}/2) or a survey's link.
type ResumeChanges ¶
type ResumeChanges struct {
Mailbox string `json:"mailbox,omitempty"`
// Group is who Exclude takes out of the rest of the send: "imported"
// (never-engaged imports, from Source when set), "lapsed" (at risk or
// sunset) or "never" (never opened). ImportedOnly is the older spelling
// of "imported".
Group string `json:"group,omitempty"`
Source string `json:"source,omitempty"`
ImportedOnly bool `json:"importedOnly"`
Exclude int64 `json:"exclude"`
Rate float64 `json:"rate,omitempty"`
Automation string `json:"automation,omitempty"`
AutomationID string `json:"automationId,omitempty"`
Expected float64 `json:"expected,omitempty"`
}
ResumeChanges is what "Resume with changes" does.
type ResumeRequest ¶
type ResumeRequest struct {
// Mailbox or ProviderID names the scope (neither = the whole campaign).
Mailbox string
ProviderID *uuid.UUID
// WithChanges applies the incident's recommended changes: exclude a
// group, lower the rate, hand the excluded contacts to a flow.
WithChanges bool
// Changes override the incident's recommendation.
Changes *ResumeChanges
// Limit raises the limit of the metric that tripped, for this send
// only, in percent (review GS-2).
Limit *float64
}
ResumeRequest resumes a mailbox provider or route on hold.
type ResumeResult ¶
type ResumeResult struct {
Excluded int64 `json:"excluded"`
Rate float64 `json:"rate,omitempty"`
Automation string `json:"automation,omitempty"`
}
ResumeResult says what resuming changed.
type RunArgs ¶
RunArgs runs a campaign's send loop for a while, then snoozes.
func (RunArgs) InsertOpts ¶
func (RunArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
type RunWorker ¶
type RunWorker struct {
river.WorkerDefaults[RunArgs]
E *Engine
}
type SeedChecker ¶
type SeedChecker interface {
StartSeeds(ctx context.Context, ws, campaignID uuid.UUID) (check uuid.UUID, seeds int, err error)
SeedPlacement(ctx context.Context, ws, check uuid.UUID) (SeedPlacement, error)
}
SeedChecker sends a campaign's content to the workspace's seed mailboxes and reads where the copies landed (the app wires internal/placement): the canary's seed gate.
type SeedMailboxResult ¶
type SeedMailboxResult struct {
Mailbox string `json:"mailbox" enum:"gmail,outlook,yahoo,icloud,other"`
Seeds int `json:"seeds"`
Inbox int `json:"inbox"`
Promotions int `json:"promotions"`
Spam int `json:"spam"`
}
SeedMailboxResult is one mailbox provider's seeds.
type SeedPlacement ¶
type SeedPlacement struct {
Inbox int `json:"inbox"`
Promotions int `json:"promotions"`
Spam int `json:"spam"`
Pending int `json:"pending"`
// Missing copies never arrived before the test ended.
Missing int `json:"missing"`
ByMailbox []SeedMailboxResult `json:"byMailbox"`
}
SeedPlacement is where the canary's seed copies landed.
type SimArgs ¶
type SimArgs struct{}
SimArgs applies the demo transport's events as they come due.
func (SimArgs) InsertOpts ¶
func (SimArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
type SimWorker ¶
type SimWorker struct {
river.WorkerDefaults[SimArgs]
E *Engine
}
type StartArgs ¶
type StartArgs struct {
CampaignID uuid.UUID `json:"campaign_id" river:"unique"`
At time.Time `json:"at" river:"unique"`
By uuid.UUID `json:"by"`
}
StartArgs starts a scheduled campaign at its time (with the send-time readiness recheck).
func (StartArgs) InsertOpts ¶
func (StartArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
type StartOptions ¶
type StartOptions struct {
// By is who starts the send.
By uuid.UUID
// Now starts right away even when the campaign is scheduled later.
Now bool
// Scenario is the demo transport's scenario (demo providers only).
Scenario string
// ABWindow replaces the A/B test's duration (demo sends).
ABWindow time.Duration
// ApprovedBy/ApprovedAt record the approval the send goes out under
// when the approvals domain has none on file.
ApprovedBy *uuid.UUID
ApprovedAt *time.Time
// ScheduledBy is who scheduled it (defaults to who last edited it).
ScheduledBy *uuid.UUID
// Scheduled is the scheduled start at its time (the start job): the
// system starts it, on behalf of who scheduled it.
Scheduled bool
// Canary is the canary choice (review GS-10, C1): auto (Traffic rules
// decide), on or off; "" keeps the campaign's (Review & send's).
Canary string
}
StartOptions tune a start beyond the Starter contract (the demo command).
type StartWorker ¶
type StartWorker struct {
river.WorkerDefaults[StartArgs]
E *Engine
}
type StateError ¶
type StateError struct {
Msg string
// contains filtered or unexported fields
}
StateError explains why an action isn't possible now. Msg is the English; In writes it in a reader's language.
func (*StateError) Error ¶
func (e *StateError) Error() string
func (*StateError) In ¶
func (e *StateError) In(l i18n.Lang) string
In is why the action isn't possible, in a reader's language.
func (*StateError) Unwrap ¶
func (e *StateError) Unwrap() error
type StoreContent ¶
type StoreContent interface {
// Resolve redraws the store blocks of an email's HTML with current
// prices and availability. Stable keeps every product in its place (a
// hidden product stays in the HTML, invisible), so the email's tracked
// links keep their positions across sends.
Resolve(ctx context.Context, workspaceID uuid.UUID, html string, stable bool) string
// Vars are a message's own link variables ("checkout_url").
Vars(ctx context.Context, msgCtx map[string]string) map[string]string
// Splice fills a rendered message's Checkout items from its context.
Splice(ctx context.Context, msgCtx map[string]string, html string) string
}
StoreContent is what store blocks need from the sending engine (internal/commerce): products read when the email goes out, and the trigger's checkout or order in automation emails.
type Template ¶
type Template struct {
// Links lists the tracked links in position order.
Links []TrackedLink
// Opens and Clicks say what the tracked variant tracks.
Opens, Clicks bool
// contains filtered or unexported fields
}
Template is an email prepared once per send: Liquid parsed, links indexed and rewritten to per-recipient tracking variables, the open pixel added. Rendering a recipient only fills in variables. A Template is safe for concurrent use.
func Prepare ¶
Prepare parses an email's Liquid once and indexes its links. Library image paths must already be absolute (media.Absolutize).
func PrepareCut ¶
PrepareCut is Prepare for one version of an email with conditional blocks: cut removes the blocks a recipient doesn't get (and the markers) after the links were numbered on the whole email, so every version keeps the link positions of campaign_links. A nil cut only removes markers.
type ThresholdChange ¶
type ThresholdChange struct {
Bounce *float64
Complaint *float64
MailboxComplaint *float64
Deferral *float64
APIErrors *float64
// Scope is "route" or "campaign" ("" leaves it).
Scope string
}
ThresholdChange is a person's change of a running or waiting send's thresholds, in percent; nil leaves one as it is.
type Thresholds ¶
type Thresholds struct {
Bounce float64 `json:"bounce"`
// Complaint applies campaign-wide; MailboxComplaint to each mailbox provider.
Complaint float64 `json:"complaint"`
MailboxComplaint float64 `json:"mailbox_complaint"`
Deferral float64 `json:"deferral"`
APIErrors float64 `json:"api_errors"`
// Scope is "route" (pause only the affected mailbox provider or sending
// provider) or "campaign" (pause everything).
Scope string `json:"scope"`
// By bounce type and level (review GS-11; Traffic rules › Thresholds
// by bounce type), each with its action: pause_mailbox, slow (to half
// rate), pause_send or warn.
//
// BlockBounce: block/policy bounces (rejections for reputation, policy
// or content) at one mailbox provider.
BlockBounce float64 `json:"block_bounce"`
BlockAction string `json:"block_action"`
// UnknownWarn and UnknownPause: unknown users (other hard bounces)
// over the whole send, two levels.
UnknownWarn float64 `json:"unknown_warn"`
UnknownWarnAction string `json:"unknown_warn_action"`
UnknownPause float64 `json:"unknown_pause"`
UnknownPauseAction string `json:"unknown_pause_action"`
// DeferralSlow and Deferral: soft bounces and deferrals at one mailbox
// provider over a window of minutes (0: the whole send so far), two
// levels.
DeferralSlow float64 `json:"deferral_slow"`
DeferralSlowWindow int `json:"deferral_slow_window"`
DeferralSlowAction string `json:"deferral_slow_action"`
DeferralWindow int `json:"deferral_window"`
DeferralAction string `json:"deferral_action"`
// ComplaintAction is what MailboxComplaint does.
ComplaintAction string `json:"complaint_action"`
}
Thresholds are the auto-pause limits of a send (campaigns.thresholds, edited on Review & send). Rates are percentages: bounce of sent, complaint of delivered, deferral of sent, API errors of calls in the last three minutes.
func ParseThresholds ¶
func ParseThresholds(campaign, workspace json.RawMessage) Thresholds
ParseThresholds resolves a send's thresholds: the defaults, then the workspace's (workspaces.send_thresholds, Settings › Providers), then the campaign's own (campaigns.thresholds, Review & send). Each level may set any limit; the spellings of both screens are read (hard_bounce or bounce; provider_error_rate, provider_errors or api_errors). The per-mailbox complaint limit follows the overall one unless set.
type TrackedLink ¶
TrackedLink is a link of the email that goes through the click redirect. Position is its index in campaign_links (and in click tokens); URL may contain Liquid, which the redirect renders for the clicking contact.
type Tracking ¶
type Tracking struct {
Opens bool `json:"opens"`
Clicks bool `json:"clicks"`
// UTM, when set, is added to the email's tracked web links before
// anything else (clicktoken.AddUTM), click tracking on or off: the
// plain variant, the text part and the addresses the click redirect
// goes to all carry it. It is decided per send, never stored with the
// campaign's tracking options.
UTM *clicktoken.UTM `json:"-"`
}
Tracking options of a campaign (campaigns.tracking).
type TrafficAction ¶
type TrafficAction struct {
At time.Time `json:"at"`
CampaignID string `json:"campaignId"`
Campaign string `json:"campaign"`
Kind string `json:"kind" enum:"threshold,reply_rule,canary,complaint_watch"`
Text string `json:"text"`
}
TrafficAction is one thing the rules did.
type TrafficReplyRule ¶
type TrafficReplyRule struct {
// ID is empty for a rule the request adds.
ID string `json:"id,omitempty"`
Mailbox string `json:"mailbox" enum:"gmail,outlook,yahoo,icloud,other"`
Contains string `json:"contains" minLength:"2" maxLength:"120" doc:"Matched as plain text, not case-sensitive, anywhere in the reply"`
// Count replies within WindowMinutes; 1 acts on the first reply.
Count int `json:"count" minimum:"1" maximum:"10000"`
WindowMinutes int `json:"windowMinutes" minimum:"1" maximum:"1440"`
Action string `json:"action" enum:"slow,pause,pause_route,alert"`
// DurationMinutes is how long the action lasts; 0 until someone
// resumes.
DurationMinutes int `json:"durationMinutes" minimum:"0" maximum:"10080"`
Enabled bool `json:"enabled"`
Note string `json:"note,omitempty" maxLength:"300" doc:"What the reply means, in the rule's own words"`
// Means is what the reply means: the note, or what ReputeCast knows of
// the reply, in the reader's language (read only).
Means string `json:"means,omitempty" readOnly:"true"`
// LastMatchedAt and LastCampaign are when it last acted, and in which
// send (read only).
LastMatchedAt *time.Time `json:"lastMatchedAt,omitempty" readOnly:"true"`
LastCampaign string `json:"lastCampaign,omitempty" readOnly:"true"`
}
TrafficReplyRule is a mailbox provider response rule.
type TrafficRules ¶
type TrafficRules struct {
Thresholds TrafficThresholds `json:"thresholds"`
ReplyRules []TrafficReplyRule `json:"replyRules"`
Canary rules.Canary `json:"canary"`
Watch rules.Watch `json:"watch"`
// Seeds is how many seed mailboxes the workspace connected (the canary
// adds them).
Seeds int `json:"seeds"`
// Resumers are the people who can resume sends: alerts go to them.
Resumers []string `json:"resumers"`
// Usual is the median audience of the workspace's last 8 sends (the
// canary's "over 2× the usual size"); 0 before there are any.
Usual int64 `json:"usual"`
// CanManage: the reader can change the rules (providers:manage).
CanManage bool `json:"canManage"`
// Recent is what the rules did in the last 30 days, newest first.
Recent []TrafficAction `json:"recent"`
SavedAt *time.Time `json:"savedAt,omitempty"`
SavedBy string `json:"savedBy,omitempty"`
}
TrafficRules is the screen.
type TrafficRulesInput ¶
type TrafficRulesInput struct {
Thresholds TrafficThresholds `json:"thresholds"`
ReplyRules []TrafficReplyRule `json:"replyRules" maxItems:"50"`
Canary rules.Canary `json:"canary"`
Watch rules.Watch `json:"watch"`
}
TrafficRulesInput is what the screen saves.
type TrafficThresholds ¶
type TrafficThresholds struct {
BlockBounce float64 `json:"blockBounce" minimum:"0.01" maximum:"20"`
BlockAction string `json:"blockAction" enum:"pause_mailbox,slow,pause_send,warn"`
UnknownWarn float64 `json:"unknownWarn" minimum:"0.1" maximum:"50"`
UnknownWarnAction string `json:"unknownWarnAction" enum:"warn,slow,pause_send"`
UnknownPause float64 `json:"unknownPause" minimum:"0.1" maximum:"50"`
UnknownPauseAction string `json:"unknownPauseAction" enum:"pause_send,warn,slow"`
DeferralSlow float64 `json:"deferralSlow" minimum:"1" maximum:"100"`
DeferralSlowWindow int `json:"deferralSlowWindow" enum:"5,10,15,30"`
DeferralSlowAction string `json:"deferralSlowAction" enum:"slow,pause_mailbox,warn"`
Deferral float64 `json:"deferral" minimum:"1" maximum:"100"`
DeferralWindow int `json:"deferralWindow" enum:"5,10,15,30"`
DeferralAction string `json:"deferralAction" enum:"pause_mailbox,slow,warn"`
Complaint float64 `json:"complaint" minimum:"0.01" maximum:"5" doc:"Complaints per mailbox provider, where they're reported"`
ComplaintAction string `json:"complaintAction" enum:"pause_mailbox,pause_send,warn"`
}
TrafficThresholds are the workspace's thresholds by bounce type and complaints per mailbox provider, in percent, each with its action.
type TransactionalFailover ¶
TransactionalFailover is a message moved to another provider of its route.
type TransactionalFailure ¶
TransactionalFailure is a message every provider of its route failed.
type TransactionalHooks ¶
type TransactionalHooks interface {
TransactionalOutcome(ctx context.Context, tx pgx.Tx, o TransactionalOutcome) error
}
TransactionalHooks is told about each outcome inside the transaction that records it.
type TransactionalOutbox ¶
type TransactionalOutbox struct {
E *Engine
// Open decodes a message's sealed payload (the transactional domain).
Open func(ctx context.Context, id uuid.UUID, sealed []byte) (providers.Message, providers.MessageExtras, error)
Hooks TransactionalHooks
// DevSMTP, in development, delivers the demo providers' transactional
// mail to the mail catcher (Mailpit) and records it as delivered.
DevSMTP string
// contains filtered or unexported fields
}
TransactionalOutbox delivers transactional messages: per provider, within the provider's per-second rate shared with campaigns and automations (ahead of Broadcasts, see transactionalHeadroom), with retries and back-off for up to ten minutes, then the route's fallback; a provider marked down sends its queue to the fallback at once.
func (*TransactionalOutbox) Kick ¶
func (o *TransactionalOutbox) Kick()
Kick asks for a pass of the outbox for mail committed before the call, and returns at once. One goroutine inserts the unique job, so a burst of sends costs a few inserts instead of one each, and no send holds the job's row: each send used to insert it in its own transaction, which locked that row until the send committed, so concurrent sends went one at a time (review 2026-11 OP-13). Mail that a lost kick leaves (the process stopping between a commit and the insert) is woken by the watch within 15 seconds.
type TransactionalOutboxArgs ¶
type TransactionalOutboxArgs struct{}
TransactionalOutboxArgs wakes the transactional outbox.
func (TransactionalOutboxArgs) InsertOpts ¶
func (TransactionalOutboxArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts: one pass waits or runs at a time; it keeps running while mail is due.
func (TransactionalOutboxArgs) Kind ¶
func (TransactionalOutboxArgs) Kind() string
Kind implements river.JobArgs.
type TransactionalOutboxWorker ¶
type TransactionalOutboxWorker struct {
river.WorkerDefaults[TransactionalOutboxArgs]
O *TransactionalOutbox
}
TransactionalOutboxWorker runs the transactional outbox.
func (*TransactionalOutboxWorker) NextRetry ¶
func (w *TransactionalOutboxWorker) NextRetry(job *river.Job[TransactionalOutboxArgs]) time.Time
NextRetry implements river.Worker.
func (*TransactionalOutboxWorker) Timeout ¶
func (w *TransactionalOutboxWorker) Timeout(*river.Job[TransactionalOutboxArgs]) time.Duration
Timeout bounds one run.
func (*TransactionalOutboxWorker) Work ¶
func (w *TransactionalOutboxWorker) Work(ctx context.Context, _ *river.Job[TransactionalOutboxArgs]) error
Work implements river.Worker.
type TransactionalOutcome ¶
type TransactionalOutcome struct {
WorkspaceID uuid.UUID
Sent []uuid.UUID
Failed []TransactionalFailure
FailedOver []TransactionalFailover
At time.Time
}
TransactionalOutcome is what one pass of the transactional outbox did for one workspace: the transactional domain emits its webhook events from it.
type TransactionalWatchArgs ¶
type TransactionalWatchArgs struct{}
TransactionalWatchArgs is the safety net: it wakes the outbox for scheduled sends and retries that came due, and fails over queues of providers marked down.
func (TransactionalWatchArgs) InsertOpts ¶
func (TransactionalWatchArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
func (TransactionalWatchArgs) Kind ¶
func (TransactionalWatchArgs) Kind() string
Kind implements river.JobArgs.
type TransactionalWatchWorker ¶
type TransactionalWatchWorker struct {
river.WorkerDefaults[TransactionalWatchArgs]
O *TransactionalOutbox
}
TransactionalWatchWorker runs TransactionalWatchArgs.
func (*TransactionalWatchWorker) Work ¶
func (w *TransactionalWatchWorker) Work(ctx context.Context, _ *river.Job[TransactionalWatchArgs]) error
Work implements river.Worker.
type WatchArgs ¶
type WatchArgs struct{}
WatchArgs is the periodic safety net: it restarts send loops whose job was lost, starts scheduled campaigns whose start job was lost, wakes the outbox and the demo transport, and purges old rate windows.
func (WatchArgs) InsertOpts ¶
func (WatchArgs) InsertOpts() river.InsertOpts
InsertOpts implements river.JobArgsWithInsertOpts.
type WatchWorker ¶
type WatchWorker struct {
river.WorkerDefaults[WatchArgs]
E *Engine
}
Source Files
¶
- ab.go
- actions.go
- analysis.go
- api.go
- audience.go
- automation.go
- bytype.go
- canary.go
- canary_live.go
- conditional.go
- demo.go
- doubt.go
- engine.go
- estimate.go
- events.go
- guard.go
- guardstate.go
- honeypot.go
- jobs.go
- kick.go
- lang.go
- languages.go
- live.go
- live_lang.go
- lock.go
- loop.go
- outages.go
- outcome.go
- rates.go
- rearm.go
- render.go
- render_errors.go
- replies.go
- rescue.go
- routeerrors.go
- sim.go
- simulate.go
- start.go
- store.go
- stream.go
- thresholds_live.go
- traffic_api.go
- transactional.go
- util.go
- vet.go
- warmup_send.go
- watch.go
- watch_live.go