engine

package
v1.0.0 Latest Latest
Warning

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

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

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

View Source
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).

View Source
const OpenVar = varOpenURL

OpenVar is the Liquid variable holding the open pixel URL.

Variables

View Source
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.

View Source
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.

View Source
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.

View Source
var ErrRender = errors.New("the email's personalization doesn't render")

ErrRender wraps personalization errors in an email.

Functions

func LinkVar

func LinkVar(position int) string

LinkVar is the Liquid variable holding the redirect URL of a link.

func MaskAddress

func MaskAddress(email string) string

MaskAddress hides most of an address for the live feed: "ana.kowalski@gmail.com" → "a.k···@gmail.com".

func Register

func Register(h huma.API, e *Engine)

Register adds the live monitor's operations.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, e *Engine)

RegisterJobs adds the sending workers and the watchdog.

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

QueueAutomationEmail implements automations.Mailer.

type Content

type Content struct {
	Subject   string
	Preheader string
	HTML      string
	Text      string
}

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
	// QuietDemo makes the demo transport report no delivery or engagement
	// events (throughput measurements of the send path alone).
	QuietDemo bool
	// contains filtered or unexported fields
}

Engine runs campaign sends and automation emails. It implements Starter.

func (*Engine) Cancel

func (e *Engine) Cancel(ctx context.Context, campaignID, by uuid.UUID) error

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

func (e *Engine) DrivePrepare(ctx context.Context, campaignID uuid.UUID, now time.Time) error

DrivePrepare builds the recipient list on a virtual clock (tests and the demo command).

func (*Engine) MoveShare

func (e *Engine) MoveShare(ctx context.Context, campaignID, by, from, to uuid.UUID) (int64, error)

MoveShare moves what is left of one provider's share to another (a person's decision during an outage).

func (*Engine) OutboxStep

func (e *Engine) OutboxStep(ctx context.Context, now time.Time) (int, error)

OutboxStep sends one second's automation emails (tests and fast-forward).

func (*Engine) Pause

func (e *Engine) Pause(ctx context.Context, campaignID, by uuid.UUID, reason string) error

Pause implements Starter: everything stops after the batches in flight.

func (*Engine) PickWinner

func (e *Engine) PickWinner(ctx context.Context, campaignID, by uuid.UUID, variant string) error

PickWinner ends an A/B test with a person's choice.

func (*Engine) Prepare

func (e *Engine) Prepare(ctx context.Context, campaignID uuid.UUID) error

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

func (e *Engine) PumpSim(ctx context.Context, now time.Time) (int, *time.Time, error)

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

func (e *Engine) Resume(ctx context.Context, campaignID, by uuid.UUID) error

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

func (e *Engine) RetryRoute(ctx context.Context, campaignID, by, provider uuid.UUID) error

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

func (e *Engine) RunOutbox(ctx context.Context, budget time.Duration) (time.Duration, bool, error)

RunOutbox sends queued automation emails per provider, within each provider's shared rate, for up to budget.

func (*Engine) Snapshot

func (e *Engine) Snapshot(ctx context.Context, wsID, campaignID uuid.UUID) (LiveSnapshot, error)

Snapshot builds the live monitor's view of a campaign.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context, campaignID, startedBy uuid.UUID) error

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) StartWith

func (e *Engine) StartWith(ctx context.Context, campaignID uuid.UUID, o StartOptions) error

StartWith is Start with options.

func (*Engine) Step

func (e *Engine) Step(ctx context.Context, rs *runState, now time.Time) (time.Duration, error)

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) 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) Watch

func (e *Engine) Watch(ctx context.Context) error

Watch is the watchdog's pass.

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

type IncidentCause struct {
	Lead string `json:"lead"`
	Body string `json:"body"`
}

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"`
}

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.

type IncidentLogLine

type IncidentLogLine struct {
	At   time.Time `json:"at"`
	Text string    `json:"text"`
	Bad  bool      `json:"bad"`
}

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 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

type LiveCostByRoute struct {
	Total   float64 `json:"total"`
	Planned float64 `json:"planned"`
}

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"`
}

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

type LiveFailover struct {
	Stream string `json:"stream"`
	To     string `json:"to"`
}

LiveFailover is another stream that moved off a provider on its own.

type LiveHelpers

type LiveHelpers struct {
	Pause []string `json:"pause"`
	Send  []string `json:"send"`
}

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.

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"`
	Share         float64    `json:"share"`
	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 {
	Short   string  `json:"short"`
	Percent float64 `json:"percent"`
}

LiveRouteShare is a provider's planned share (the route line).

type LiveShare

type LiveShare struct {
	Key     string  `json:"key"`
	Name    string  `json:"name"`
	Percent float64 `json:"percent"`
}

LiveShare is one slice of a breakdown.

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.
	SharedStreams  []string         `json:"sharedStreams"`
	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"`
}

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.

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

type LiveThrottle struct {
	Mailbox string  `json:"mailbox"`
	Rate    float64 `json:"rate"`
}

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.

func (OutboxArgs) Kind

func (OutboxArgs) Kind() string

Kind implements river.JobArgs.

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 PrepareArgs

type PrepareArgs struct {
	CampaignID uuid.UUID `json:"campaign_id" river:"unique"`
}

PrepareArgs builds a campaign's recipient list.

func (PrepareArgs) InsertOpts

func (PrepareArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (PrepareArgs) Kind

func (PrepareArgs) Kind() string

Kind implements river.JobArgs.

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

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 Rendered

type Rendered struct {
	Subject string
	HTML    string
	Text    string
}

Rendered is one recipient's email.

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

type RunArgs struct {
	CampaignID uuid.UUID `json:"campaign_id" river:"unique"`
}

RunArgs runs a campaign's send loop for a while, then snoozes.

func (RunArgs) InsertOpts

func (RunArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (RunArgs) Kind

func (RunArgs) Kind() string

Kind implements river.JobArgs.

type RunWorker

type RunWorker struct {
	river.WorkerDefaults[RunArgs]
	E *Engine
}

func (*RunWorker) NextRetry

func (w *RunWorker) NextRetry(job *river.Job[RunArgs]) time.Time

NextRetry implements river.Worker.

func (*RunWorker) Timeout

func (w *RunWorker) Timeout(*river.Job[RunArgs]) time.Duration

func (*RunWorker) Work

func (w *RunWorker) Work(ctx context.Context, job *river.Job[RunArgs]) error

Work implements river.Worker.

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.

func (SimArgs) Kind

func (SimArgs) Kind() string

Kind implements river.JobArgs.

type SimWorker

type SimWorker struct {
	river.WorkerDefaults[SimArgs]
	E *Engine
}

func (*SimWorker) NextRetry

func (w *SimWorker) NextRetry(job *river.Job[SimArgs]) time.Time

NextRetry implements river.Worker.

func (*SimWorker) Timeout

func (w *SimWorker) Timeout(*river.Job[SimArgs]) time.Duration

func (*SimWorker) Work

func (w *SimWorker) Work(ctx context.Context, _ *river.Job[SimArgs]) error

Work implements river.Worker.

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.

func (StartArgs) Kind

func (StartArgs) Kind() string

Kind implements river.JobArgs.

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
}

func (*StartWorker) NextRetry

func (w *StartWorker) NextRetry(job *river.Job[StartArgs]) time.Time

NextRetry implements river.Worker.

func (*StartWorker) Work

func (w *StartWorker) Work(ctx context.Context, job *river.Job[StartArgs]) error

Work implements river.Worker.

type StateError

type StateError struct{ Msg string }

StateError explains why an action isn't possible now.

func (*StateError) Error

func (e *StateError) Error() string

func (*StateError) Unwrap

func (e *StateError) Unwrap() error

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

func Prepare(c Content, t Tracking) (*Template, error)

Prepare parses an email's Liquid once and indexes its links. Library image paths must already be absolute (media.Absolutize).

func (*Template) Render

func (t *Template) Render(vars map[string]any, tracked bool) (Rendered, error)

Render fills in one recipient. vars come from liquid.Vars plus the per-recipient links; tracked selects our pixel and click redirects.

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 struct {
	Position int
	URL      string
	Label    string
}

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"`
}

Tracking options of a campaign (campaigns.tracking).

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.

func (WatchArgs) Kind

func (WatchArgs) Kind() string

Kind implements river.JobArgs.

type WatchWorker

type WatchWorker struct {
	river.WorkerDefaults[WatchArgs]
	E *Engine
}

func (*WatchWorker) Work

func (w *WatchWorker) Work(ctx context.Context, _ *river.Job[WatchArgs]) error

Work implements river.Worker.

Jump to

Keyboard shortcuts

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