api

package
v0.110.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 206 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation ¶

Overview ¶

Coverage resource definitions shared by validation and storage.

Package api is the HTTP API server.

Index ¶

Constants ¶

View Source
const AIAnswerShareNote = "" /* 210-byte string literal not displayed */

AIAnswerShareNote is returned on every payload. The figures are counted from already-stored AI visibility runs only.

View Source
const AlertErrorIssue = "error.new_issue"

AlertErrorIssue is the alert kind.

View Source
const AlertInsightThreshold = "insight.threshold"

AlertInsightThreshold is the alert kind.

View Source
const AlertTeamMailSharing = "crm_mail.team_sharing"

AlertTeamMailSharing tells a member their brand's work mail will be shared with the brand.

View Source
const AlertTrackerLinkBroken = "tracker.link_broken"

AlertTrackerLinkBroken is the alert for a page a tracker link sends to that stopped answering.

View Source
const AlertTrackingDomainExpiring = "tracking_domain.expiring"

AlertTrackingDomainExpiring is the alert for a tracking domain whose registration runs out soon or has run out.

View Source
const (

	// CreditDays is how long after a signal revenue still counts as its
	// credit.
	CreditDays = 90
)
View Source
const DefaultLogRetention = 30 * 24 * time.Hour

DefaultLogRetention is how long request logs are kept unless the operator sets OUTFLARE_LOG_RETENTION_DAYS.

View Source
const MaxSavedPeople = 10_000

MaxSavedPeople is how many people one saved list takes from a funnel.

View Source
const (

	// SignupConfirmPath is where the confirmation link points, with the
	// token in its #fragment; the host serves the page that finishes there.
	SignupConfirmPath = "/signup/confirm"
)

Variables ¶

View Source
var (
	ErrMissionInvalid = errors.New("invalid mission")
	ErrMissionDenied  = errors.New("not allowed to start missions")
	// ErrMissionRetired is every StartMission's error now: missions are
	// retired (410 mission_retired over the API).
	ErrMissionRetired = errors.New("missions retired")
)

ErrMissionInvalid is a draft the API would refuse with 400; its message says why. ErrMissionDenied is a caller who may not start missions (403).

View Source
var (
	ErrAgentRunInvalid = errors.New("invalid agent run")
	ErrAgentRunDenied  = errors.New("not allowed to start agent runs")
)

ErrAgentRunInvalid is a draft the API would refuse with 400; its message says why. ErrAgentRunDenied is a caller who may not start runs (403).

View Source
var ErrAgentGone = errors.New("the agent's token was revoked or expired")

ErrAgentGone means the agent's token was revoked or expired, or its person disabled, so it can't act any more.

View Source
var ErrAgentSpec = errors.New("invalid agent")

ErrAgentSpec is a spec the engine refuses; the message says why.

View Source
var ErrBadSignupLink = errors.New("this sign-up link is invalid, already used or expired")

ErrBadSignupLink is a sign-up link that is unknown, used or expired.

View Source
var ErrChoosePassword = errors.New("choose a password to finish signing up")

ErrChoosePassword is returned by FinishSignup when the link is opened in another browser than the one that filled in the form: the person must choose a password there, since the form's may have been a stranger's.

View Source
var ErrEmailTaken = errors.New("an account with this email already exists")

ErrEmailTaken is returned by CreateAccount when a user already has the email.

View Source
var ErrSupportAccessOff = errors.New("this person has turned support access off")

ErrSupportAccessOff is StartSupportView's answer for a person who turned support access off, or whose account is disabled.

View Source
var Version = "dev"

Version is set at build time with -ldflags "-X .../api.Version=...".

Functions ¶

func CheckAITool ¶ added in v0.8.0

func CheckAITool(t AITool) error

CheckAITool says what is wrong with an extension's tool, or nil: its id must be a tool id the engine has no tool of its own under, and its model task one a workspace can choose a model for.

func ClientIP ¶

func ClientIP(r *http.Request) string

ClientIP is the visitor's address, for rate limits and session records. Behind a proxy (Fly.io, Cloudflare) every connection comes from the proxy, so set Options.ClientIPHeader to the header it sends, such as Fly-Client-IP or CF-Connecting-IP. Only do that behind such a proxy: a direct visitor could send the header themselves.

func NormalizeTag ¶ added in v0.28.0

func NormalizeTag(v any) (any, error)

NormalizeTag makes a tag lowercase, trimmed and at most 50 characters, so "VIP " and "vip" are one tag.

func RequestID ¶

func RequestID(ctx context.Context) string

RequestID returns the request's id, for logs and audit events.

func WriteError ¶

func WriteError(w http.ResponseWriter, r *http.Request, status int, code, message string)

WriteError writes the standard error body: {"error": {"code", "message", "request_id"}}.

func WriteJSON ¶

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as JSON with a status.

Types ¶

type AIConnection ¶ added in v0.80.0

type AIConnection struct {
	ID       string
	Provider llm.Provider
	Name     string
}

AIConnection is one of the workspace's connected AI model connections.

type AITool ¶ added in v0.8.0

type AITool struct {
	ID, Name, Description, ModelTask string
}

AITool is an extension's own AI tool: a name for its calls on the usage page, so a workspace sees what they cost and can give them a limit. Its calls use the model the workspace chose for ModelTask, a model task such as classify_domain, so they need no model setting of their own.

type Accounts ¶

type Accounts struct {
	Pool      *pgxpool.Pool
	PublicURL string
	Box       *secrets.Box // opens Google sign-ins (NewAccount.Identity)
	Mailer    sysmail.Sender
	Log       *slog.Logger
	// SignedInCookieDomain is Options.SignedInCookieDomain.
	SignedInCookieDomain string
}

Accounts lets builds on top of the engine, such as the hosted Cloud, sign people up and recognise them with the engine's own users and sessions, without copying its password or token formats. Reached through outflare.Host.Accounts.

func (*Accounts) CreateAccount ¶

func (a *Accounts) CreateAccount(ctx context.Context, tx pgx.Tx, w http.ResponseWriter, r *http.Request, in NewAccount) (userID, workspaceID string, err error)

CreateAccount creates a user who owns a new workspace and signs them in on w, in one transaction with tx's other writes (pass nil for its own). Bad input returns an error whose message can be shown to the person.

func (*Accounts) DeleteUser ¶

func (a *Accounts) DeleteUser(ctx context.Context, tx pgx.Tx, userID string) (UserDeletion, error)

DeleteUser deletes a person for good, in tx: their workspaces that nobody else uses, their sign-ins (sessions, passwords, Google, passkeys), their memberships and pending account emails. In shared workspaces their past actions stay but are shown as "Deleted user", and an owner is promoted if they were the only one.

func (*Accounts) DeleteWorkspace ¶

func (a *Accounts) DeleteWorkspace(ctx context.Context, tx pgx.Tx, workspaceID string) error

DeleteWorkspace deletes a workspace and everything in it, in tx. Its members keep their accounts. It returns pgx.ErrNoRows when there is no such workspace.

func (*Accounts) EndSupportViews ¶ added in v0.8.0

func (a *Accounts) EndSupportViews(ctx context.Context, q interface {
	Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
}, viewerID string) error

EndSupportViews ends every view by viewerID, such as when they stop being staff.

func (*Accounts) FinishSignup ¶

func (a *Accounts) FinishSignup(ctx context.Context, tx pgx.Tx, w http.ResponseWriter, r *http.Request, token, password string) (userID, workspaceID string, err error)

FinishSignup opens a sign-up link: it makes the account (its email confirmed) and its first workspace, and signs the person in on w, in tx with tx's other writes (nil for its own). password is needed only when the link is opened in another browser (ErrChoosePassword).

func (*Accounts) PlanUserDeletion ¶

func (a *Accounts) PlanUserDeletion(ctx context.Context, tx pgx.Tx, userID string) (UserDeletion, error)

PlanUserDeletion works out what DeleteUser would do, without changing anything. It returns pgx.ErrNoRows when there is no such user.

func (*Accounts) SendPasswordReset ¶

func (a *Accounts) SendPasswordReset(ctx context.Context, userID string) (string, error)

SendPasswordReset emails userID a link to choose a new password, the same email as "Forgot password". It returns the address it went to.

func (*Accounts) SendVerification ¶

func (a *Accounts) SendVerification(ctx context.Context, userID string) error

SendVerification emails userID a link to confirm their address, unless it is confirmed already (as with a Google sign-up). Call it after the transaction that created the account commits.

func (*Accounts) SessionUser ¶

func (a *Accounts) SessionUser(r *http.Request) (userID, email string, err error)

SessionUser is the signed-in person behind r's session, as a user id and email. Both are empty for an anonymous request or an API token.

func (*Accounts) StartSignup ¶

func (a *Accounts) StartSignup(ctx context.Context, w http.ResponseWriter, r *http.Request, in NewAccount) error

StartSignup checks a password sign-up and emails a confirmation link. It returns an *InputError for bad input and otherwise nil, whatever the address: an existing account gets a different email, not a different answer. Asking again sends at most one email a minute and five an hour.

func (*Accounts) StartSupportView ¶ added in v0.8.0

func (a *Accounts) StartSupportView(ctx context.Context, w http.ResponseWriter, viewerID, userID string) (SupportView, error)

StartSupportView lets viewerID, a staff member the caller has already checked, see userID's account read-only in this browser, by setting the view's cookie on w. It ends any other view by the same staff member. The caller records who started it and why.

func (*Accounts) VerifyAgentApp ¶

func (a *Accounts) VerifyAgentApp(ctx context.Context, clientID string, verified bool) (bool, error)

VerifyAgentApp marks a self-registered app as checked by the operator, so people can give it more than reading; verified false takes that back (its connections drop to reading on their next refresh). It answers false when there is no such app.

type AgentRunDraft ¶ added in v0.81.0

type AgentRunDraft struct {
	Name, Goal, Instructions, Plan string
	// BrandID keeps the run and its token to one brand; required for a
	// brand-limited caller.
	BrandID *string
	// Mode is copilot (the default: every change waits for a person),
	// autonomous (changes run within MaxSpendCents) or dry_run.
	Mode          string
	MaxSpendCents *int64
	// Note is the run's first update; empty for "Started by …".
	Note string
}

AgentRunDraft is an agent run an extension starts for the caller, such as a loop's brief, as POST /v1/workspaces/{ws}/playbooks/{id}/agent-runs does for a playbook: Outflare's agent carries it out in turns as an agent token of its own on the action layer, and the mode sets what it may do on its own. It replaces MissionDraft for new loops.

type AgentSpec ¶ added in v0.80.0

type AgentSpec struct {
	WorkspaceID string
	// Name shows in the audit log and on the Agents page, such as "Brand
	// agent: Acme". Up to 200 characters.
	Name string
	// Scopes the agent holds: never more than an operator's, and never one
	// only a person may hold.
	Scopes []string
	// BrandID keeps the token to one brand, or nil for every brand.
	BrandID *string
	// CreatedBy is the id of the person on whose say-so the loop runs, or
	// "". A disabled person's agents stop with them.
	CreatedBy string
}

AgentSpec describes the agent token an extension creates for a loop.

type BlobStore ¶ added in v0.110.0

type BlobStore interface {
	Put(ctx context.Context, key, contentType string, body []byte) error
	Get(ctx context.Context, key string) ([]byte, error)
	Delete(ctx context.Context, key string) error
}

BlobStore keeps a recording's parts: the server's bucket.

type BrandKnowledge ¶ added in v0.86.0

type BrandKnowledge struct {
	Summary  string                     `json:"summary"`
	Industry string                     `json:"industry"`
	Lists    map[string][]KnowledgeItem `json:"lists"`
	// Pages are the addresses the last read took it from.
	Pages []string `json:"pages"`
}

BrandKnowledge is what the website says, as a person may edit it.

func (BrandKnowledge) Empty ¶ added in v0.86.0

func (k BrandKnowledge) Empty() bool

Empty reports whether nothing was read or written yet.

func (BrandKnowledge) Text ¶ added in v0.86.0

func (k BrandKnowledge) Text() string

Text writes the knowledge for a model's prompt, "" when empty.

func (*BrandKnowledge) UnmarshalJSON ¶ added in v0.86.0

func (k *BrandKnowledge) UnmarshalJSON(b []byte) error

UnmarshalJSON reads the model's answer (bullets by page number) and a stored or edited knowledge (bullets by URL) alike.

type Caller ¶

type Caller struct {
	WorkspaceID string
	// ActorID is the person's or token's actor; ActorType "human" or
	// "api_token".
	ActorID, ActorType string
	// UserID is the person, also for their API tokens; empty for a token
	// whose maker has left.
	UserID string
	// Role is the person's workspace role, empty for tokens.
	Role string
	// Brands limits the caller to some brands; nil is every brand.
	Brands []string
	// Brand is the brand a brand route is on (WorkspaceRoute.Brand), and
	// empty on a workspace route.
	Brand string
	// Test is true in a test workspace.
	Test bool
	// contains filtered or unexported fields
}

Caller is who is making a workspace request, and what they may do.

func (*Caller) AddLinkProspects ¶ added in v0.78.0

func (c *Caller) AddLinkProspects(ctx context.Context, tx pgx.Tx, site seosync.ProspectSite, source string, list []seosync.Prospect) (seosync.ProspectsAdded, error)

AddLinkProspects adds pages to site's link prospect list in tx, as the caller, recording link_prospect.found for each new one. The caller must be able to change site's brand; the pages are already checked (seosync.ProspectPage, a known method, not on the site itself).

func (*Caller) Decode ¶

func (c *Caller) Decode(w http.ResponseWriter, r *http.Request, v any) bool

Decode reads a JSON body, refusing unknown fields, and answers 400 when it cannot.

func (*Caller) Has ¶

func (c *Caller) Has(scope string) bool

Has reports whether the caller has a scope.

func (*Caller) Internal ¶

func (c *Caller) Internal(w http.ResponseWriter, r *http.Request, err error)

Internal logs err and answers 500 without saying what went wrong.

func (*Caller) Record ¶

func (c *Caller) Record(ctx context.Context, tx pgx.Tx, action, targetType, targetID string, data map[string]any) error

Record writes an audit event for the caller in tx, which is also the product event of the same name once the request succeeds.

func (*Caller) Sees ¶

func (c *Caller) Sees(brand *string) bool

Sees reports whether the caller may see something of a brand (nil for shared).

func (*Caller) StartAgentRun ¶ added in v0.81.0

func (c *Caller) StartAgentRun(ctx context.Context, tx pgx.Tx, d AgentRunDraft) (string, error)

StartAgentRun starts an agent run for the caller in tx: the caller needs agents.run, the run gets a token and grants from its mode, its first turn is due at once, and agent_run.created is recorded. It returns the run's id.

func (*Caller) StartMission ¶ added in v0.37.0

func (c *Caller) StartMission(ctx context.Context, tx pgx.Tx, d MissionDraft) (string, error)

StartMission is retired with missions: it always returns ErrMissionRetired. Loops start agent runs with StartAgentRun instead. It stays so extensions built against it keep compiling until it is removed.

func (*Caller) Writes ¶

func (c *Caller) Writes(brand *string) bool

Writes reports whether the caller may change something of a brand (nil for shared). A brand-limited caller only reads shared things.

type CertState ¶ added in v0.8.0

type CertState struct {
	Status string // pending, active or failed
	// Error says what to fix when Status is failed, or why it is still
	// pending when the provider knows.
	Error string
}

CertState is where a tracking domain's certificate stands.

type ClickHouseArchive ¶ added in v0.81.0

type ClickHouseArchive struct{ CH *eventstore.ClickHouse }

ClickHouseArchive lets rule dry runs read the ClickHouse event store (Options.EventArchive), which keeps every event, beyond Postgres's retention.

func (ClickHouseArchive) RuleEvents ¶ added in v0.81.0

func (c ClickHouseArchive) RuleEvents(ctx context.Context, ws, name string, since time.Time, limit int) ([]rules.ArchivedEvent, error)

RuleEvents implements rules.EventArchive.

type DeletionWorkspace ¶

type DeletionWorkspace struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	NewOwner string `json:"new_owner_email,omitempty"`
}

DeletionWorkspace is one workspace in a UserDeletion.

type InputError ¶

type InputError struct{ Msg string }

InputError is a validation failure whose message is safe to show.

func (*InputError) Error ¶

func (e *InputError) Error() string

type KnowledgeItem ¶ added in v0.86.0

type KnowledgeItem struct {
	Text string `json:"text"`
	URL  string `json:"url"`
}

type MCPUpstream ¶

type MCPUpstream struct {
	URL    *url.URL
	Secret string
}

MCPUpstream is where the hosted MCP server listens, and the secret that proves a request came through the engine.

type MenuBadges func(ctx context.Context, workspaceID string) (map[string]string, error)

MenuBadges returns short texts an extension shows next to its own sidebar links for one workspace, by link id, such as {"billing": "$50.00"}.

type MenuLink struct {
	// ID is a stable name for the link, such as "admin".
	ID string `json:"id"`
	// Label is what the sidebar shows, such as "Admin".
	Label string `json:"label"`
	// Href is the page it opens: a path on this server, such as "/admin".
	Href string `json:"href"`
	// Icon names one of the web app's icons, such as "shield".
	Icon string `json:"icon"`
}

MenuLink is an extra item an extension adds to one person's sidebar, such as the hosted Cloud's staff console for staff. It arrives in /v1/me as menu_links, so only the people it is for ever see it; the page it opens still checks who is calling.

type MenuLinks func(ctx context.Context, userID string) ([]MenuLink, error)

MenuLinks returns the links one signed-in person gets, or none.

type MissionDraft ¶ added in v0.37.0

type MissionDraft struct {
	Name, Goal, Instructions, Plan string
	// Mode is dry_run (the default), approve_writes or autonomous.
	Mode          string
	MaxSpendCents *int64
	EndsAt        *time.Time
}

MissionDraft is a mission an extension starts for the caller, such as a loop's brief. Like any mission it does nothing until a person approves it, and everything it does goes through the API's gate, limits and audit log.

type NewAccount ¶

type NewAccount struct {
	Email, Name, Password, WorkspaceName string
	// Identity, instead of Password, is a Google sign-in from
	// /v1/auth/google/callback (its identity parameter). Its verified email
	// is the account's; Email may be empty or must match it.
	Identity string
}

NewAccount is a person signing up with their first workspace.

type Options ¶

type Options struct {
	WebDir    string // built web app to serve; empty disables
	PublicURL string // external base URL, used in links and to decide Secure cookies
	Mailboxes *mailbox.Service
	Sending   *sending.Engine
	Inbox     *inbox.Syncer
	OAuth     *oauth.Tokens // "Continue with Google"; nil disables it
	// Allocation plans which mailboxes serve which sequences; nil builds one.
	Allocation *allocation.Service
	Box        *secrets.Box // seals OAuth states for connectors
	// Connectors and email verification; nil disables them.
	Integrations *connectors.Store
	Verify       *verify.Service
	// EmailFinder proposes and verifies addresses from a workspace's learned
	// patterns; nil turns the /email-finder endpoints off.
	EmailFinder *emailfind.Service
	// DataNetwork is the data network's membership and lookups
	// (internal/datanetwork); it works without a network registered.
	DataNetwork *datanetwork.Service
	// InboundEmail receives workspaces' forwarded mail when an extension
	// turned it on (package inboundemail); nil leaves it off.
	InboundEmail *inboundemail.Service
	// Classifier says what kind of email domain an address is; nil builds
	// one on the built-in data that asks the system resolver.
	Classifier *classify.Classifier
	// Research reads an unknown domain's homepage with the workspace's own
	// connector and AI key; nil leaves unknown domains unresearched.
	Research *research.Service
	// Lists builds lead lists from data providers; nil disables builds.
	Lists *lists.Service
	// Mailbox supplier sync (Cheap Inboxes and the like); nil disables it.
	Vendors *vendorsync.Service
	// Inbound receives connectors' webhooks (live updates); nil turns
	// /v1/hooks and the live update endpoints off.
	Inbound   *inbound.Service
	Imports   *imports.Service   // moving over from other sequencers
	Platforms *platforms.Service // outside sequencers in mailbox allocation; nil disables syncing on demand
	// Verifies tracking domains; defaults to the system resolver.
	CNAME tracking.CNAMEResolver
	// Outcome syncs (calendars, CRMs); nil disables syncing on demand.
	Outcomes *outcomes.Syncer
	// AnalyticsSync stores analytics history; nil turns the sync endpoints off.
	AnalyticsSync *analyticsync.Syncer
	// SEOSync keeps weekly SEO snapshots; nil turns POST .../seo/{id}/sync off.
	SEOSync *seosync.Syncer
	// AdSync reads connected ad accounts; nil turns POST .../ads/sync off.
	AdSync *adsync.Syncer
	// DomainConnect finds domains' DNS providers for the one-off "apply
	// these records?" screen; nil builds one on the public internet and
	// the system resolver, signing with a key the server stores.
	DomainConnect *domainconnect.Client
	// Crawl runs OutflareBot's crawls and ownership checks; nil builds one
	// that checks DNS with the system resolver.
	Crawl *crawl.Service
	// Anonymous usage stats and update checks; nil builds one that sends
	// nothing.
	Telemetry *telemetry.Reporter
	// RateLimit is how many requests an API token may make a minute; 0
	// means no limit.
	RateLimit int
	// Webhooks sends test events and redeliveries; nil builds one that only
	// delivers to public https URLs.
	Webhooks *webhooks.Service
	// EventArchive is the ClickHouse event store, when one is set up: rule
	// dry runs replay events from it over up to a year.
	EventArchive rules.EventArchive
	// Sends account emails (confirmation, password reset); nil only logs
	// them.
	Mailer sysmail.Sender
	// Passkeys turns on passkey sign-in, for PUBLIC_URL's host. Only set it
	// once PUBLIC_URL is the address people will always use: passkeys made
	// for one address don't work on another.
	Passkeys bool
	// ClientIPHeader is the header a trusted proxy in front of the server
	// puts the visitor's address in, such as Fly-Client-IP. Empty uses the
	// connection's address.
	ClientIPHeader string
	// PostHogKey turns on product analytics in the web app, sent through
	// /ingest/ on this server to PostHogHost (https://us.i.posthog.com by
	// default). Empty sends nothing.
	PostHogKey  string
	PostHogHost string
	// MCP is the hosted MCP server to proxy /mcp to; nil serves no /mcp.
	MCP *MCPUpstream
	// Emails sends lifecycle and transactional email through the
	// workspace's email providers; nil builds one when Integrations and
	// Box are set (its jobs run only where the queue registers it).
	Emails *emails.Service
	// PrivacyURL and TermsURL are the operator's policies, linked from the
	// OAuth metadata when set.
	PrivacyURL, TermsURL string
	// CommunityLinks shows the optional "Star us on GitHub" and "Follow us
	// on X" items (GET /v1/me/community); CommunityXURL is the X profile,
	// empty to leave that item out. CommunityBuilderURL is the X profile of
	// the person building Outflare in public ("Follow the builder"), empty
	// to leave it out.
	CommunityLinks      bool
	CommunityXURL       string
	CommunityBuilderURL string
	// SignedInCookieDomain, when set, is a parent domain of PUBLIC_URL's
	// host (outflare.ai for app.outflare.ai) where the server keeps an
	// outflare_signed_in=1 cookie while someone is signed in, so a website
	// on that domain can show a link to the app instead of Sign in. Empty
	// sets no such cookie.
	SignedInCookieDomain string
	// SiteInbox makes POST /v1/site/events only queue browser events in
	// site_event_inbox and answer; RunSiteInbox, on a server that works,
	// stores them. Off stores them during the request.
	SiteInbox bool
	// Recordings is the bucket session recordings are kept in
	// (OUTFLARE_S3_*). Nil leaves recordings off; heatmaps need none.
	Recordings BlobStore
	// Files is the bucket brands' files are kept in (logos, fonts,
	// product shots; OUTFLARE_S3_*). Nil leaves uploads off.
	Files BlobStore
	// Video finishes and edits talking videos on the server (ffmpeg).
	// Nil leaves those steps out: videos are made without them.
	Video VideoTool

	// Extension points for builds that add to the open-source engine, such
	// as the hosted Cloud. See the outflare package.
	Routes func(mux *http.ServeMux) // extra routes, registered before the /v1/ catch-all
	// WorkspaceRoutes are extension routes behind the workspace check.
	WorkspaceRoutes []WorkspaceRoute
	Middleware      []func(http.Handler) http.Handler // wrap every request, outermost first, inside request ids and logging
	Capabilities    []string                          // added to /v1/meta
	// MenuLinks add per-person sidebar items, in /v1/me.
	MenuLinks []MenuLinks
	// MenuBadges add short per-workspace texts next to extension links
	// (GET /v1/workspaces/{ws}/menu-badges).
	MenuBadges []MenuBadges
	// AITools name extensions' own AI calls on the usage page.
	AITools []AITool
	// SupportAuto says which workspaces the support assistant may answer
	// customers in without a person; nil for none (it only drafts).
	SupportAuto func(ctx context.Context, workspaceID string) bool
	// AdAutoApprove says whether an agent may approve a paid ads
	// suggestion that saves money, for a brand and kind, without a person;
	// nil for never (only a person approves).
	AdAutoApprove func(ctx context.Context, workspaceID, brandID, kind string) bool
	// TrackingTarget is the host tracking domains' CNAME records point at;
	// empty for PUBLIC_URL's host.
	TrackingTarget string
	// PartnersDomain serves partner portals at <subdomain>.<it>; empty for
	// /p/<program>/ only.
	PartnersDomain string
	// TrackingCerts gets HTTPS certificates for tracking domains; nil when
	// the operator's own proxy serves them.
	TrackingCerts TrackingCerts
	// Quota may refuse new brands, mailboxes, tracking domains and records
	// (package quota); nil allows everything.
	Quota quota.Checker
	// EdgeSecret lets an edge in front of tracking domains pass on the
	// domain and visitor address it saw (edge.go); empty turns that off.
	EdgeSecret string
	// QueryConnections is how many queries run at once, each on its own
	// database connection; zero means the default (3), below zero turns
	// Query off.
	QueryConnections int
}

Options configures a Server.

type Server ¶

type Server struct {
	// contains filtered or unexported fields
}

func NewServer ¶

func NewServer(pool *pgxpool.Pool, log *slog.Logger, opts Options) *Server

func (*Server) AIConnectionsOf ¶ added in v0.80.0

func (s *Server) AIConnectionsOf(ctx context.Context, ws string) ([]AIConnection, error)

AIConnectionsOf lists the workspace's connected AI model connections, for a feature that calls several models (each with its own way of searching the web) rather than the one the workspace chose.

func (*Server) AIModelOn ¶ added in v0.80.0

func (s *Server) AIModelOn(ctx context.Context, ws, task, integrationID, model string, cents int64) (research.Choice, error)

AIModelOn opens one of the workspace's AI connections with model (empty: the workspace's model when it is that connection, else the provider's default) for task, refusing when the task's or the workspace's monthly AI limit would not cover about cents more. A model whose price Outflare doesn't know runs only on a router that reports what each call cost.

func (*Server) AIModels ¶

func (s *Server) AIModels() research.Models

AIModels is the engine's implementation of research.Models.

func (*Server) AIModelsOn ¶ added in v0.110.0

func (s *Server) AIModelsOn(ctx context.Context, ws, integrationID string) (llm.Provider, []llm.ModelInfo, error)

AIModelsOn lists the chat models one of the workspace's connected AI connections can use, asked of its provider with the workspace's own key, for a feature that lets the workspace pick a model of that connection.

func (*Server) AIVisibilityModels ¶

func (s *Server) AIVisibilityModels() aivis.Models

AIVisibilityModels is the engine's implementation of aivis.Models.

func (*Server) AIVisibilityScreens ¶ added in v0.86.0

func (s *Server) AIVisibilityScreens() aivis.Screens

AIVisibilityScreens is the engine's implementation of aivis.Screens.

func (*Server) ActAsAgent ¶ added in v0.97.0

func (s *Server) ActAsAgent(ctx context.Context, ws, brand, agentID, method, path string, body json.RawMessage, reason, key string) (int, []byte, error)

ActAsAgent makes one change in a brand as one of the workspace's agents, for a journey's outflare_action step (journeys.AgentCaller). The agent is an API token of the workspace whose changes go through the action layer, kept to that brand or to none, so its grants decide what runs, what waits for a person and what is refused. path is the part after /v1/brands/{brand}/.

func (*Server) AdvanceVideo ¶ added in v0.110.0

func (s *Server) AdvanceVideo(ctx context.Context, ws, id string) error

AdvanceVideo takes a video as far as it can go: through the stages done on the server, up to one that waits for a provider. It is safe to call at any time and from several workers: a stage that is already running is waited for, never started twice.

func (*Server) CallAsAgent ¶ added in v0.80.0

func (s *Server) CallAsAgent(ctx context.Context, tokenID, method, path string, body json.RawMessage, reason string) (int, []byte, error)

CallAsAgent makes one API call in process as an agent token: path is a full API path ("/v1/workspaces/{ws}/sequences", "/v1/brands/{id}/rules"), body is JSON or nil, and reason is what the agent says it is doing, kept with the action. The answer is the handler's: a change the gate held answers 202 with the action, one it refused 403 action_refused.

func (*Server) CheckInstalls ¶

func (s *Server) CheckInstalls(ctx context.Context)

CheckInstalls runs one pass of RunSetup now.

func (*Server) CheckRedditAction ¶ added in v0.48.0

func (s *Server) CheckRedditAction(ctx context.Context, ws, id string) error

CheckRedditAction reads a sent action on Engain and Reddit now.

func (*Server) CheckSocialWatch ¶

func (s *Server) CheckSocialWatch(ctx context.Context, ws, id string) error

CheckSocialWatch searches the watch's channel, stores what matches, has the AI draft replies when the watch asks, and refreshes the results of recent actions.

func (*Server) CheckTrackerPages ¶ added in v0.110.0

func (s *Server) CheckTrackerPages(ctx context.Context, pause time.Duration) (int, error)

CheckTrackerPages asks the landers and offers that are due, up to landerCheckBatch of each, waiting pause between them. It returns how many it asked. Only one worker runs it at a time.

func (*Server) CheckTrackingDomainExpiry ¶ added in v0.110.0

func (s *Server) CheckTrackingDomainExpiry(ctx context.Context, pause time.Duration) (int, error)

CheckTrackingDomainExpiry reads the registration of the verified tracking domains that are due, up to domainExpiryBatch, waiting pause between reads so the public RDAP service isn't hurried. It returns how many it read. Only one worker runs it at a time.

func (*Server) ConvertTransactions ¶ added in v0.81.0

func (s *Server) ConvertTransactions(ctx context.Context) (int, error)

ConvertTransactions converts what it can of the transactions with no brand amount yet, and says how many it converted.

func (*Server) CountUnassigned ¶ added in v0.83.0

func (s *Server) CountUnassigned(ctx context.Context) error

CountUnassigned sets the unassigned connections gauge across every workspace.

func (*Server) CreateAgentToken ¶ added in v0.80.0

func (s *Server) CreateAgentToken(ctx context.Context, tx pgx.Tx, spec AgentSpec) (string, error)

CreateAgentToken makes a loop's token in tx: on the action layer, with no secret kept, so only the engine can act as it (CallAsAgent).

func (s *Server) DiscoverBrandLinks(ctx context.Context, ws, brandID string) error

DiscoverBrandLinks reads a brand's homepage through the workspace's page reader and stores the profiles and listings it links to as suggestions. A page built in the browser, or one that turned the first read away, is read again with JavaScript on. A bot check or a slow page is the site's own refusal (blocked, slow_page): it is kept on the brand for the Links panel to show, and never retried, since it would only fail the same way.

func (*Server) DiscoverReviewPages ¶ added in v0.8.0

func (s *Server) DiscoverReviewPages(ctx context.Context, ws, brandID string) error

DiscoverReviewPages searches the web for a brand's review pages through the workspace's own web search connection (Geonode) and suggests the ones that match the brand. Nothing is added on its own.

func (*Server) DraftReviewReply ¶ added in v0.8.0

func (s *Server) DraftReviewReply(ctx context.Context, ws, id string, last bool) error

DraftReviewReply has the workspace's own AI write a drafting reply. When the AI can't (no model, no budget, a bad answer on the last try) the draft fails with the reason.

func (*Server) DraftSocialAction ¶

func (s *Server) DraftSocialAction(ctx context.Context, ws, id string, last bool) error

DraftSocialAction has the workspace's own AI write a drafting action. When the AI can't (no model, no budget, a bad answer on the last try) the action fails with the reason, and the post is open for a person.

func (*Server) DraftSocialPublication ¶ added in v0.18.0

func (s *Server) DraftSocialPublication(ctx context.Context, ws, id string, last bool) error

DraftSocialPublication has the workspace's own AI write a publication that is drafting. When the AI can't (no model, no budget, a bad answer on the last try) it goes back to a draft with the reason, for a person to write.

func (*Server) DrainSiteInbox ¶

func (s *Server) DrainSiteInbox(ctx context.Context) (int, error)

DrainSiteInbox gives every workspace with waiting events one turn and reports how many inbox rows it finished (stored or set aside).

func (*Server) ExpireHandEdits ¶ added in v0.81.0

func (s *Server) ExpireHandEdits(ctx context.Context) (int, error)

ExpireHandEdits handles the hand edits whose time ran out, a batch at a time, and reports how many. Each goes in its own transaction: the field takes the value of the best other source that gave one (by the field's precedence, then the newest), as a normal change in the record's history that rules hear of. With no other value it stays, marked expired, and the next source to write the field replaces it.

func (*Server) ExpirePrivacyExports ¶ added in v0.62.0

func (s *Server) ExpirePrivacyExports(ctx context.Context) (int, error)

ExpirePrivacyExports deletes the files of exports past their expiry and fails exports stuck pending, and returns how many expired.

func (*Server) FlushClicks ¶ added in v0.90.0

func (s *Server) FlushClicks(ctx context.Context) error

FlushClicks writes every buffered click now. A batch that fails goes back to wait for the next flush, unless the database refused it for what a click holds: then waiting changes nothing, so the batch is written in halves and only the click at fault is dropped.

func (*Server) FlushLogs ¶

func (s *Server) FlushLogs(ctx context.Context) error

FlushLogs writes request logs still queued, for a clean shutdown.

func (*Server) Handler ¶

func (s *Server) Handler() http.Handler

Handler returns the full HTTP handler with middleware applied. It is built once; approved mission actions run through it too.

func (*Server) JourneyAI ¶ added in v0.39.0

func (s *Server) JourneyAI() journeys.AI

JourneyAI is the engine's implementation of journeys.AI.

func (*Server) KeepForecasts ¶ added in v0.110.0

func (s *Server) KeepForecasts(ctx context.Context, now time.Time) (int, error)

KeepForecasts saves a reading for every brand that has a deal or a forecast target and no reading in the last 20 hours, and reports how many it saved. Each brand goes in its own transaction, so one that fails doesn't hold up the rest.

func (*Server) LookUpDueAddresses ¶ added in v0.95.0

func (s *Server) LookUpDueAddresses(ctx context.Context) (int, error)

LookUpDueAddresses claims one batch of due addresses and looks them up, and reports how many it claimed.

func (*Server) MoveDeal ¶ added in v0.35.0

func (s *Server) MoveDeal(ctx context.Context, tx pgx.Tx, ws, recordID string, d journeys.DealMove, ref string) (string, string, error)

MoveDeal is the engine's journeys.DealMover: a journey's move_deal step moves the person's open deal the same way a reply rule does, and with the same source, so it never overrides a stage a person set.

func (*Server) OpenRenewalDeals ¶ added in v0.97.0

func (s *Server) OpenRenewalDeals(ctx context.Context, tx pgx.Tx, ws, recordID, stage string, within int, ref string) (string, string, error)

OpenRenewalDeals is the engine's journeys.DealMover for open_renewal_deal: for the company, and for each record that names it as its company (an agreement), whose "Renews on" date is within the next days, it opens a deal at stage (the first stage when empty) with the renewal's value, closing on the renewal date. Where deals have an owner field it is the company's owner; the forecast counts the deal for the company's owner either way. A renewal that has had a deal for that date gets no second one, whatever became of the first.

func (*Server) ProductEventSink ¶

func (s *Server) ProductEventSink(ctx context.Context, ws, brand string) (track.Sink, error)

ProductEventSink returns the sink that stores product events in workspace ws, under brand (its id or handle; "" is the workspace's first brand), the one whose website tag counts the operator's own visitors, so people join their visits. It fails when either doesn't exist.

func (*Server) PruneClickAddresses ¶ added in v0.95.0

func (s *Server) PruneClickAddresses(ctx context.Context) (int64, error)

PruneClickAddresses deletes kept click addresses older than 30 days, and lookup results older than 400.

func (*Server) PruneEventInbox ¶ added in v0.62.0

func (s *Server) PruneEventInbox(ctx context.Context) (int, error)

PruneEventInbox deletes event inbox rows past their retention, a batch at a time, and returns how many it deleted.

func (*Server) PruneIdempotencyKeys ¶

func (s *Server) PruneIdempotencyKeys(ctx context.Context) (int64, error)

PruneIdempotencyKeys deletes keys older than a day. The engine runs it hourly.

func (*Server) PruneInboundWebhookIDs ¶

func (s *Server) PruneInboundWebhookIDs(ctx context.Context) (int64, error)

PruneInboundWebhookIDs forgets the ids of suppliers' webhook deliveries after 30 days. Suppliers retry for hours, not weeks, so that is long enough to drop every repeat; the table no longer grows forever.

func (*Server) PruneJobs ¶

func (s *Server) PruneJobs(ctx context.Context) (int64, error)

PruneJobs deletes finished jobs after 14 days, a batch at a time, and returns how many it deleted. Jobs with an idempotency key stay, because the key is what stops that work being queued twice, except the kinds in prunableKeyedJobs: one runs per event or per batch of events, so they grow with traffic, and their keys name an id made in the same transaction (an event, a batch) or a time slot long past, so nothing asks for them again after a day, let alone 14.

func (*Server) PruneKnowledgeBin ¶ added in v0.29.0

func (s *Server) PruneKnowledgeBin(ctx context.Context) (int64, error)

PruneKnowledgeBin deletes knowledge that has been in the bin for more than knowledgeBinDays, a batch at a time.

func (*Server) PruneOAuthCodes ¶

func (s *Server) PruneOAuthCodes(ctx context.Context) (int64, error)

PruneOAuthCodes deletes authorization codes an hour after they expire, and apps that registered but were never approved within a day.

func (*Server) PrunePageVitals ¶ added in v0.87.0

func (s *Server) PrunePageVitals(ctx context.Context) (int64, error)

PrunePageVitals deletes readings older than 90 days, a batch at a time.

func (*Server) PrunePartnerConversionLog ¶ added in v0.74.0

func (s *Server) PrunePartnerConversionLog(ctx context.Context) (int64, error)

PrunePartnerConversionLog deletes logged conversion calls older than 30 days.

func (*Server) PruneQueryEndpointCalls ¶ added in v0.81.0

func (s *Server) PruneQueryEndpointCalls(ctx context.Context) (int64, error)

PruneQueryEndpointCalls deletes the call log of query endpoints after 90 days.

func (*Server) PruneRequestLogs ¶

func (s *Server) PruneRequestLogs(ctx context.Context, keep time.Duration) (int64, error)

PruneRequestLogs deletes request logs older than keep (DefaultLogRetention when zero), a batch at a time so a large backlog never holds a long lock.

func (*Server) PruneTrackerConversionLog ¶ added in v0.92.0

func (s *Server) PruneTrackerConversionLog(ctx context.Context) (int64, error)

PruneTrackerConversionLog deletes logged calls older than 30 days.

func (*Server) PruneWebhookDeliveries ¶

func (s *Server) PruneWebhookDeliveries(ctx context.Context) (int64, error)

PruneWebhookDeliveries deletes deliveries older than 30 days.

func (*Server) PublishSocialPublication ¶ added in v0.18.0

func (s *Server) PublishSocialPublication(ctx context.Context, ws, id string, last bool) error

PublishSocialPublication posts an approved publication whose time has come, once. It is marked publishing before the call; only a rate limit the channel answered before posting anything is retried, and a call that may have gone through is never sent again.

func (*Server) PurgeAICalls ¶

func (s *Server) PurgeAICalls(ctx context.Context) int64

PurgeAICalls runs one pass of RunAIUsage now and returns how many calls it deleted.

func (*Server) PurgeDeletions ¶ added in v0.64.0

func (s *Server) PurgeDeletions(ctx context.Context) (int, error)

PurgeDeletions removes deletions past their 7 days for good, and returns how many: what they hold is deleted, and a deleted record is erased as DELETE .../records/{record} would (with the records merged into it). A restored deletion's row goes too.

func (*Server) QueueDueABTestChecks ¶ added in v0.27.0

func (s *Server) QueueDueABTestChecks(ctx context.Context) (int, error)

QueueDueABTestChecks moves each due running test's next check on and queues it, in one transaction, and reports how many it queued.

func (*Server) QueueDueBrandKnowledge ¶ added in v0.93.0

func (s *Server) QueueDueBrandKnowledge(ctx context.Context) (int, error)

QueueDueBrandKnowledge turns on the daily read for every brand with a connected ad account (whichever path connected it) and queues the reads due: brands with the daily read on, a website, and no read in the last 23 hours. It says how many it queued.

func (*Server) QueueDueCoverage ¶ added in v0.69.0

func (s *Server) QueueDueCoverage(ctx context.Context) (int, error)

QueueDueCoverage only observes and creates maintenance work. It never chooses an outreach action, sends a message or purchases a placement.

func (*Server) QueueDueInsightAlertChecks ¶ added in v0.85.0

func (s *Server) QueueDueInsightAlertChecks(ctx context.Context) (int, error)

QueueDueInsightAlertChecks moves each due rule's next check on and queues it, in one transaction, and reports how many it queued.

func (*Server) QueueDueMentionScans ¶ added in v0.110.0

func (s *Server) QueueDueMentionScans(ctx context.Context) (int, error)

QueueDueMentionScans moves each due brand's next scan on and queues it, in one transaction, and reports how many it queued.

func (*Server) QueueDueNewsSearches ¶ added in v0.21.0

func (s *Server) QueueDueNewsSearches(ctx context.Context) (int, error)

QueueDueNewsSearches moves each due search's next run on and queues it, in one transaction, and reports how many it queued.

func (*Server) QueueDuePricingReads ¶ added in v0.86.0

func (s *Server) QueueDuePricingReads(ctx context.Context) (int, error)

QueueDuePricingReads queues a read through the first page reader of each workspace with a pricing page due, once an hour. A read only reads the pages that are due.

func (*Server) QueueDueReddit ¶ added in v0.48.0

func (s *Server) QueueDueReddit(ctx context.Context) (int, error)

QueueDueReddit queues the checks that are due, sends approved actions whose job was lost, and settles sends that died mid-call. It reports how many jobs it queued.

func (*Server) QueueDueReviewReads ¶ added in v0.8.0

func (s *Server) QueueDueReviewReads(ctx context.Context) (int, error)

QueueDueReviewReads queues a read through each page reader in a workspace whose brands link to a review page, once an hour. A read only reads the pages that are due, so this costs nothing until one is.

func (*Server) QueueDueSocialChecks ¶

func (s *Server) QueueDueSocialChecks(ctx context.Context) (int, error)

QueueDueSocialChecks moves each due watch's next check on and queues it, in one transaction, and reports how many it queued.

func (*Server) QueueDueSocialPublications ¶ added in v0.18.0

func (s *Server) QueueDueSocialPublications(ctx context.Context) (int, error)

QueueDueSocialPublications queues approved publications whose time has passed and whose own job has not posted them, and settles ones whose job died mid-call. It reports how many it queued.

func (*Server) QueueDueSocialSyncs ¶

func (s *Server) QueueDueSocialSyncs(ctx context.Context) (int, error)

QueueDueSocialSyncs queues a sync for each connection with an account that is due (every hour, so a failed read is tried again the same day), for each connection with no accounts yet (twice a day), and for each page reader in a workspace whose brands link to a profile (every hour, so a profile no read has started for yet, such as one linked before its channel could be read, starts within the hour; a sync reads only the accounts that are due, so this costs no reads), and reports how many it queued.

func (*Server) QueueSemanticEmbeds ¶ added in v0.4.0

func (s *Server) QueueSemanticEmbeds(ctx context.Context) (int, error)

QueueSemanticEmbeds runs one tick of RunSemanticSearch and reports how many jobs it queued.

func (*Server) QueueSupportImports ¶ added in v0.110.0

func (s *Server) QueueSupportImports(ctx context.Context) (int, error)

QueueSupportImports runs one tick of RunSupportImports and says how many passes it started. Servers ticking together start each once (the lock).

func (*Server) QueueWebsiteRechecks ¶ added in v0.81.0

func (s *Server) QueueWebsiteRechecks(ctx context.Context) (int, error)

QueueWebsiteRechecks runs one tick of RunWebsiteRechecks and says how many re-checks it queued. One workspace gets one at a time, and servers ticking together queue each once (the lock).

func (*Server) ReadBrandKnowledge ¶ added in v0.86.0

func (s *Server) ReadBrandKnowledge(ctx context.Context, ws, brandID string) error

ReadBrandKnowledge reads a brand's website through the workspace's page reader and has its AI model write what the brand offers.

func (*Server) ReadBrandLook ¶ added in v0.93.0

func (s *Server) ReadBrandLook(ctx context.Context, ws, brandID string) error

ReadBrandLook reads a brand's home page for its logo and theme colour and saves the ones the brand doesn't have yet. A site that can't be read or offers neither leaves the brand as it was.

func (*Server) ReadMentionEpisode ¶ added in v0.110.0

func (s *Server) ReadMentionEpisode(ctx context.Context, ws, id string) error

ReadMentionEpisode reads the transcript a found episode's show publishes, keeps it, and keeps each place the brand or a tracked competitor is named in it, with the second when the transcript is timed. A mention already kept from the show notes gets the spoken quote and second.

func (*Server) ReadMentionVideo ¶ added in v0.110.0

func (s *Server) ReadMentionVideo(ctx context.Context, ws, id string) error

ReadMentionVideo reads a found video's watch page (who made it, how many saw it, when) and its captions, keeps them, and keeps each place the brand or a tracked competitor is named in what was said, with the second it was said. A mention already kept from the video's title gets the spoken quote and second. Failures the workspace can fix (no page reading connection, a spent usage limit) set the video aside; a provider outage is tried again.

func (*Server) ReadPricingPages ¶ added in v0.86.0

func (s *Server) ReadPricingPages(ctx context.Context, ws, integrationID string) error

ReadPricingPages reads the workspace's due pricing pages through one page reader. One page's failure doesn't stop the others; an outage or a used-up quota of the reader stops the round and is retried with the job.

func (*Server) ReadReviewPages ¶ added in v0.8.0

func (s *Server) ReadReviewPages(ctx context.Context, ws, integrationID string) error

ReadReviewPages reads the review pages that are due through one page reader. One page's failure doesn't stop the others. An outage is retried with the job, and a failure Outflare has to fix (a page it couldn't save) fails the job so it shows in job.failed too.

func (*Server) RegisterJobs ¶

func (s *Server) RegisterJobs(q *jobs.Queue)

RegisterJobs adds the server's own background work to the queue.

func (*Server) RevokeAgentToken ¶ added in v0.80.0

func (s *Server) RevokeAgentToken(ctx context.Context, tx pgx.Tx, workspaceID, tokenID, byUserID string) error

RevokeAgentToken revokes a loop's token in tx, on the say-so of the person byUserID (or the system when empty), with its audit event. A token already revoked, or not this workspace's, is left as it is.

func (*Server) RunABTestAI ¶ added in v0.21.0

func (s *Server) RunABTestAI(ctx context.Context, ws, id string, last bool) error

RunABTestAI runs one queued AI run on the workspace's own model. When the AI can't (no model, no budget, a bad answer on the last try), the run fails with the reason in words.

func (*Server) RunABTests ¶ added in v0.27.0

func (s *Server) RunABTests(ctx context.Context, every time.Duration)

RunABTests queues the checks of running tests that are due, every interval, until ctx ends.

func (*Server) RunAIUsage ¶

func (s *Server) RunAIUsage(ctx context.Context, every time.Duration)

RunAIUsage deletes calls older than the retention window, in batches so it never holds a long lock, every interval until ctx ends.

func (*Server) RunAgentRuns ¶ added in v0.83.0

func (s *Server) RunAgentRuns(ctx context.Context, every time.Duration)

RunAgentRuns takes the due turns of agent runs until ctx ends, looking every interval.

func (*Server) RunAutomations ¶ added in v0.54.1

func (s *Server) RunAutomations(ctx context.Context, every time.Duration)

RunAutomations starts playbook automations' runs as they fall due, until ctx ends.

func (*Server) RunBrandKnowledgeRefresh ¶ added in v0.93.0

func (s *Server) RunBrandKnowledgeRefresh(ctx context.Context, every time.Duration)

RunBrandKnowledgeRefresh queues the daily reads of brands' websites that are due, every interval.

func (*Server) RunClicks ¶ added in v0.90.0

func (s *Server) RunClicks(ctx context.Context)

RunClicks writes buffered redirect clicks until ctx ends, then writes what is left. Every process that serves redirect links runs it.

func (*Server) RunConnectionBrands ¶ added in v0.83.0

func (s *Server) RunConnectionBrands(ctx context.Context)

RunConnectionBrands reports how many connections and accounts have no brand, for the dashboard, until ctx ends.

func (*Server) RunCreativeSkillDraft ¶ added in v0.110.0

func (s *Server) RunCreativeSkillDraft(ctx context.Context, ws, id string, last bool) error

RunCreativeSkillDraft drafts a skill for one queued description on the workspace's own model. When the AI can't (no model, no budget, a bad answer on the last try), the draft fails with the reason in words.

func (*Server) RunDueAgentTurns ¶ added in v0.80.0

func (s *Server) RunDueAgentTurns(ctx context.Context) (int, error)

RunDueAgentTurns runs every agent run turn that is due now, a few at a time, and reports how many ran.

func (*Server) RunDueAutomations ¶ added in v0.54.1

func (s *Server) RunDueAutomations(ctx context.Context) (int, error)

RunDueAutomations looks at every automation that is due, one at a time, and reports how many runs it started.

func (*Server) RunEventInbox ¶ added in v0.62.0

func (s *Server) RunEventInbox(ctx context.Context)

RunEventInbox keeps the event inbox healthy until ctx ends: it reports how many events wait and how long, queues processing for brands whose events have waited too long (a job lost or out of retries), and deletes rows at the end of their retention.

func (*Server) RunForecastHistory ¶ added in v0.110.0

func (s *Server) RunForecastHistory(ctx context.Context, every time.Duration)

RunForecastHistory keeps each brand's forecast reading every interval, until ctx ends.

func (*Server) RunGeneration ¶ added in v0.110.0

func (s *Server) RunGeneration(ctx context.Context, ws, id string) error

RunGeneration takes a generation one step on: sends it to the provider, or asks how a request the provider is still working on is doing, and keeps the file once there is one. It queues its own next look while the provider works. A request is sent once: when a step dies between sending and noting the answer, the generation fails rather than being sent (and paid for) again.

func (*Server) RunHandEditExpiry ¶ added in v0.81.0

func (s *Server) RunHandEditExpiry(ctx context.Context, every time.Duration)

RunHandEditExpiry hands expired hand edits over every interval, until ctx ends.

func (*Server) RunIPLookups ¶ added in v0.95.0

func (s *Server) RunIPLookups(ctx context.Context, every time.Duration)

RunIPLookups looks up due click addresses every interval, at once again while a pass finds a full batch, until ctx ends.

func (*Server) RunInsightAlerts ¶ added in v0.85.0

func (s *Server) RunInsightAlerts(ctx context.Context, every time.Duration)

RunInsightAlerts queues the checks of the rules that are due, every interval, until ctx ends.

func (*Server) RunInsightQuestion ¶ added in v0.110.0

func (s *Server) RunInsightQuestion(ctx context.Context, ws, id string, last bool) error

RunInsightQuestion answers one queued question on the workspace's own model. When the AI can't (no model, no budget, a bad answer on the last try), the question fails with the reason in words.

func (*Server) RunNetworkCosts ¶ added in v0.97.0

func (s *Server) RunNetworkCosts(ctx context.Context, every time.Duration)

RunNetworkCosts reconciles network cost every interval until ctx ends.

func (*Server) RunNewsSearch ¶ added in v0.21.0

func (s *Server) RunNewsSearch(ctx context.Context, ws, searchID string) error

RunNewsSearch runs one search through the workspace's own web search connection, books what it cost, and keeps the articles it found: for a coverage search, those that name the brand's query and aren't on its own site become coverage. A failure is kept on the search (last_error_code) and is an event; the job is retried when the provider was unavailable or rate limited, and the search runs again soon (retry.After) either way.

func (*Server) RunPageChecks ¶ added in v0.110.0

func (s *Server) RunPageChecks(ctx context.Context, every time.Duration)

RunPageChecks checks due landers and offers every interval until ctx ends.

func (*Server) RunPartnerRewards ¶ added in v0.22.0

func (s *Server) RunPartnerRewards(ctx context.Context)

RunPartnerRewards approves held rewards whose hold has ended, in programs that approve on their own, until ctx ends.

func (*Server) RunPayments ¶

func (s *Server) RunPayments(ctx context.Context)

RunPayments queues payment syncs until ctx ends.

func (*Server) RunPrivacyExports ¶ added in v0.62.0

func (s *Server) RunPrivacyExports(ctx context.Context)

RunPrivacyExports expires privacy exports until ctx ends: a ready export past its 7 days loses its file, and one pending far too long (its job is dead) fails.

func (*Server) RunQueryQuestion ¶ added in v0.110.0

func (s *Server) RunQueryQuestion(ctx context.Context, ws, id string, last bool) error

RunQueryQuestion answers one queued question on the workspace's own model. When the AI can't (no model, no budget, a bad answer on the last try), the question fails with the reason in words.

func (*Server) RunRecoveryWindow ¶ added in v0.64.0

func (s *Server) RunRecoveryWindow(ctx context.Context)

RunRecoveryWindow purges deletions past their 7 days until ctx ends.

func (*Server) RunReplaySweep ¶ added in v0.110.0

func (s *Server) RunReplaySweep(ctx context.Context)

RunReplaySweep deletes recordings a person deleted, that are past their brand's keep_days or that ended shorter than its min_seconds, file first, and heatmap counts past 90 days.

func (*Server) RunSalesFeeds ¶ added in v0.110.0

func (s *Server) RunSalesFeeds(ctx context.Context, every time.Duration)

RunSalesFeeds queues a read of every channel that is due, every interval until ctx ends.

func (*Server) RunSemanticSearch ¶ added in v0.4.0

func (s *Server) RunSemanticSearch(ctx context.Context, every time.Duration)

RunSemanticSearch queues an embedding job for each workspace with meaning-based search on that has none waiting, every tick.

func (*Server) RunSetup ¶

func (s *Server) RunSetup(ctx context.Context, every time.Duration)

RunSetup keeps looking for the proof of sites waiting on a DNS record, and works out install health, until ctx ends.

func (*Server) RunSiteInbox ¶

func (s *Server) RunSiteInbox(ctx context.Context, poll time.Duration)

RunSiteInbox stores the browser events waiting in site_event_inbox until ctx ends: straight away while there are any, then on a wake from this process's collector or every poll.

func (*Server) RunSmartListDraft ¶ added in v0.110.0

func (s *Server) RunSmartListDraft(ctx context.Context, ws, id string, last bool) error

RunSmartListDraft writes rules for one queued description on the workspace's own model. When the AI can't (no model, no budget, a bad answer on the last try), the draft fails with the reason in words.

func (*Server) RunSocial ¶

func (s *Server) RunSocial(ctx context.Context, every time.Duration)

RunSocial queues checks for watches that are due, every tick.

func (*Server) RunSocialAction ¶

func (s *Server) RunSocialAction(ctx context.Context, ws, id string, last bool) error

RunSocialAction runs an approved action on its connection. It never runs twice: only a refusal the channel answered before doing anything (a rate limit) is retried, and a call that may have gone through is not sent again.

func (*Server) RunSupportImports ¶ added in v0.110.0

func (s *Server) RunSupportImports(ctx context.Context, every time.Duration)

RunSupportImports starts the next pass of each caught-up import every few minutes, retries failed ones, restarts stuck ones, and reports how far behind the imports are.

func (*Server) RunTrackingDomainExpiry ¶ added in v0.110.0

func (s *Server) RunTrackingDomainExpiry(ctx context.Context, every time.Duration)

RunTrackingDomainExpiry reads due tracking domains' registrations every interval until ctx ends.

func (*Server) RunTransactionRates ¶ added in v0.81.0

func (s *Server) RunTransactionRates(ctx context.Context, every time.Duration)

RunTransactionRates fills in the brand amounts of transactions saved before their day's exchange rate was known, every interval.

func (*Server) RunWebsiteRechecks ¶ added in v0.81.0

func (s *Server) RunWebsiteRechecks(ctx context.Context, every time.Duration)

RunWebsiteRechecks keeps imported websites current: every tick, each website imported into knowledge whose last import finished more than a day ago is read again (a scheduled import with the same settings), so changed pages update, new ones are added and removed ones unpublished.

func (*Server) ScanBrandMentions ¶ added in v0.110.0

func (s *Server) ScanBrandMentions(ctx context.Context, ws, brand string) (int, error)

ScanBrandMentions reads what the brand's sources found since its last scan, keeps every new place the brand or a tracked competitor is named, and reports how many it kept. A brand with mentions off is skipped.

func (*Server) SendRedditAction ¶ added in v0.48.0

func (s *Server) SendRedditAction(ctx context.Context, ws, id string) error

SendRedditAction sends an approved action to Engain, once.

func (*Server) SetAdAutoApprove ¶ added in v0.85.0

func (s *Server) SetAdAutoApprove(fn func(ctx context.Context, workspaceID, brandID, kind string) bool)

SetAdAutoApprove replaces the hook that lets agents approve saving suggestions (Options.AdAutoApprove), for tests.

func (*Server) SetSupportAuto ¶ added in v0.80.0

func (s *Server) SetSupportAuto(fn func(ctx context.Context, workspaceID string) bool)

SetSupportAuto lets an extension decide which workspaces the support assistant may answer customers in without a person (Auto mode).

func (*Server) SmartListQueryIDs ¶ added in v0.81.0

func (s *Server) SmartListQueryIDs(ctx context.Context, ws, listID string) ([]string, error)

SmartListQueryIDs runs a query list's saved query (its current version) and returns the records in its record_id column, or its id column. It reads customer data only (customers.read), inside the list's brand, as any query on the brand's route does. smartlists.Service calls it.

func (*Server) StartTrackingHTTPS ¶ added in v0.8.0

func (s *Server) StartTrackingHTTPS(ctx context.Context) error

StartTrackingHTTPS asks for certificates for verified tracking domains that have none yet, such as those verified before the server had a provider, and checks again on pending ones nothing is checking. Their links use the server's own address until each is active.

func (*Server) SweepReplay ¶ added in v0.110.0

func (s *Server) SweepReplay(ctx context.Context) (int, error)

SweepReplay does one round of RunReplaySweep and returns how many recordings it removed.

func (*Server) SyncNetworkCosts ¶ added in v0.97.0

func (s *Server) SyncNetworkCosts(ctx context.Context) (int, error)

SyncNetworkCosts runs one pass over every active traffic source whose network reports spend, and reports how many campaign days it reconciled.

func (*Server) SyncSocialAccounts ¶

func (s *Server) SyncSocialAccounts(ctx context.Context, ws, integrationID string) error

SyncSocialAccounts finds the accounts a connection reaches and reads the ones that are due. A failure is kept on the accounts and in the events; an outage is tried again by the accounts' own back-off, and the job itself fails only for what Outflare must fix (a read it couldn't save).

func (*Server) WriteField ¶ added in v0.28.0

func (s *Server) WriteField(ctx context.Context, tx pgx.Tx, ws, recordID, field, change string, value any, overwriteManual bool, ref string) (string, string, error)

WriteField changes one field of a record for a journey step, with the same checks, history and source precedence as PATCH .../records/{id}. change is set, clear or increment, or add and remove for a field that holds a list (tags). The write's source is first_party, so it never overwrites a value a person set by hand, unless overwriteManual; then the step reports it skipped with why. ref is the journey run, kept in the audit data.

It reports done or skipped with a reason, and failed (with a message) for a step that can't work, such as an unknown field or a bad value.

type SupportView ¶ added in v0.8.0

type SupportView struct {
	ID        string
	ExpiresAt time.Time
}

SupportView is a view StartSupportView began.

type TrackingCerts ¶ added in v0.8.0

type TrackingCerts interface {
	// Ensure asks for a certificate for domain, or reports on the one
	// already asked for. Calling it again for the same domain is safe.
	Ensure(ctx context.Context, domain string) (CertState, error)
	// Remove stops serving domain and drops its certificate. A domain
	// that is already gone is not an error.
	Remove(ctx context.Context, domain string) error
}

TrackingCerts gets HTTPS certificates for workspaces' tracking domains, for a server whose own proxy can't (an extension can ask a certificate provider for one per domain). Without one, the operator's proxy serves HTTPS for tracking domains as it does for PUBLIC_URL.

type UserDeletion ¶

type UserDeletion struct {
	// Deleted are workspaces nobody else is a member of. They go with
	// everything in them: mailboxes, leads, sequences, messages, connections.
	Deleted []DeletionWorkspace `json:"workspaces_deleted"`
	// Kept are workspaces shared with others. The person leaves them; if
	// they were the only owner, NewOwner (the longest-standing admin, else
	// the longest-standing member) becomes the owner.
	Kept []DeletionWorkspace `json:"workspaces_kept"`
}

UserDeletion says what deleting a person does to their workspaces.

type VideoTool ¶ added in v0.110.0

type VideoTool interface {
	Probe(ctx context.Context, data []byte) (videofx.Info, error)
	Tighten(ctx context.Context, audio []byte, gap float64) ([]byte, error)
	Finish(ctx context.Context, video []byte, look videofx.Look) ([]byte, error)
	Cut(ctx context.Context, video []byte, from, to float64) ([]byte, error)
	Splice(ctx context.Context, base, part []byte, from, to float64) ([]byte, error)
	Frame(ctx context.Context, video []byte, at float64) ([]byte, error)
}

VideoTool finishes and edits videos on the server (videofx.Tool, which runs ffmpeg). Nil on a server without ffmpeg: videos are still made, without the finish and without edits.

type WorkspaceRoute ¶

type WorkspaceRoute struct {
	// Pattern is a net/http pattern with {ws}, such as
	// "POST /v1/workspaces/{ws}/cloud/lead-finder/runs".
	Pattern string
	// Scope is what the caller needs, such as "lists.manage".
	Scope string
	// Handler serves the request. Brand-limited callers are let in, so it
	// keeps them to their brands with Caller.Sees and Caller.Writes.
	Handler func(w http.ResponseWriter, r *http.Request, c *Caller)
	// Brand puts the route under /v1/brands/{brand}/...: the engine finds
	// the brand's workspace, answers 404 to a caller who can't see the
	// brand, and sets Caller.Brand.
	Brand bool
}

WorkspaceRoute is an extension's route under /v1/workspaces/{ws}/...

Source Files ¶

Jump to

Keyboard shortcuts

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