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 RegisterTransactional(reg *jobs.Registry, o *TransactionalOutbox)
- type AutomationMailer
- type Conditional
- type Content
- type DemoSendOptions
- type DemoSendResult
- type Engine
- 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) 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) 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) 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) 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) Subscribe(ctx context.Context, ws, campaign uuid.UUID) (<-chan LiveSnapshot, func())
- func (e *Engine) Watch(ctx context.Context) error
- type Excluded
- type IncidentCause
- type IncidentDetail
- type IncidentLogLine
- type IncidentOption
- type IncidentRate
- type LanguageVersions
- type LiveAB
- type LiveABVariant
- type LiveActionResult
- type LiveCancelRequest
- type LiveCostByRoute
- type LiveDetails
- type LiveEvent
- type LiveExcluded
- type LiveFailover
- type LiveHelpers
- type LiveIncident
- type LiveMailbox
- type LiveMoveRequest
- type LiveOptions
- type LivePauseRequest
- type LiveProvider
- type LiveResumeRequest
- type LiveRetryRequest
- type LiveRouteShare
- type LiveShare
- type LiveSnapshot
- type LiveThreshold
- type LiveThrottle
- type LiveTotals
- type LiveWinnerRequest
- 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 SimArgs
- type SimWorker
- type StartArgs
- type StartOptions
- type StartWorker
- type StateError
- type StoreContent
- type Template
- type Thresholds
- type TrackedLink
- type Tracking
- type TransactionalFailover
- type TransactionalFailure
- type TransactionalHooks
- type TransactionalOutbox
- type TransactionalOutboxArgs
- type TransactionalOutboxWorker
- type TransactionalOutcome
- type TransactionalWatchArgs
- type TransactionalWatchWorker
- type WatchArgs
- type WatchWorker
Constants ¶
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 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: 5.0, APIErrors: 5.0, Scope: "route"}
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 RegisterTransactional ¶
func RegisterTransactional(reg *jobs.Registry, o *TransactionalOutbox)
RegisterTransactional adds the transactional outbox's workers.
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), records the message and wakes the outbox, all inside the engine's transaction.
func (AutomationMailer) QueueAutomationEmail ¶
func (m AutomationMailer) QueueAutomationEmail(ctx context.Context, tx pgx.Tx, o automations.OutgoingEmail) (automations.QueuedEmail, error)
QueueAutomationEmail implements automations.Mailer.
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
}
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
// contains filtered or unexported fields
}
Engine runs campaign sends and automation emails. It implements Starter.
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) 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) MoveShare ¶
MoveShare moves what is left of one provider's share to another (a person's decision during an outage).
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) Resume ¶
Resume implements Starter: a paused campaign sends again, and every mailbox provider or route on hold is released.
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, as is or with the recommended changes.
func (*Engine) RetryRoute ¶
RetryRoute keeps a held share on its provider and retries every minute; if it is still down after 15 minutes, a person is asked again.
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) 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.
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"`
}
Excluded counts the contacts of the audience who don't receive the send.
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"`
// 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"`
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"`
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 LiveActionResult ¶
type LiveActionResult struct {
Moved int64 `json:"moved"`
Cancelled int64 `json:"cancelled"`
Excluded int64 `json:"excluded"`
Snapshot LiveSnapshot `json:"snapshot"`
}
LiveActionResult is what an action changed, with the new snapshot.
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"`
}
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 LiveHelpers ¶
LiveHelpers are up to two members who hold each action's permission.
type LiveIncident ¶
type LiveIncident struct {
ID string `json:"id"`
Kind string `json:"kind" enum:"threshold,provider_outage,throttled,recheck_blocked"`
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"`
}
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 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"`
OpenRate *float64 `json:"openRate,omitempty"`
Throttle *float64 `json:"throttle,omitempty" doc:"Messages per second; absent = the provider's full rate"`
Held bool `json:"held"`
HeldSince *time.Time `json:"heldSince,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 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"`
Cost float64 `json:"cost"`
PlannedCost float64 `json:"plannedCost"`
Retrying bool `json:"retrying"`
RetryUntil *time.Time `json:"retryUntil,omitempty"`
}
LiveProvider is one sending provider's row.
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"`
}
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"`
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"`
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"`
// 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,complaint,mailbox_complaint,api_errors"`
Value float64 `json:"value"`
Limit float64 `json:"limit"`
Mailbox string `json:"mailbox,omitempty"`
}
LiveThreshold is a rate against its auto-pause limit.
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"`
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"`
}
LiveTotals are the campaign's counts.
type LiveWinnerRequest ¶
type LiveWinnerRequest struct {
Variant string `json:"variant" enum:"A,B,C"`
}
LiveWinnerRequest picks the A/B winner.
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"`
}
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
}
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 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
}
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 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"`
}
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 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
}
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) Run ¶
func (o *TransactionalOutbox) Run(ctx context.Context, budget time.Duration) (time.Duration, bool, error)
Run sends due transactional mail for up to budget.
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
}