segments

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Overview

Package segments implements audience segments (spec 5.10, 7.9): a condition builder with AND/OR groups compiled to parameterized SQL, a live count with the tier mix, the generated SQL shown to power users, and SQL mode (segments:sql) where people write read-only SQL over the segment views. Static segments keep a snapshot of their members.

Index

Constants

View Source
const (
	CodeSQLError    = "sql_error"
	CodeSQLDisabled = "sql_disabled"
	CodeTimeout     = "count_timeout"
)

Problem codes of this package.

View Source
const (
	FieldPaidStatus = "paid_status"
	FieldPaidTier   = "paid_tier"
	FieldPaidPeriod = "paid_period"
	FieldPaidSince  = "paid_since"
	FieldPaidEnded  = "paid_ended"
	FieldPaidLTV    = "paid_ltv"
)

The paid subscription fields.

View Source
const (
	FieldPushSite        = "push_site"
	FieldPushBrowser     = "push_browser"
	FieldWhatsAppConsent = "whatsapp_consent"
)

The push and WhatsApp fields.

View Source
const AnyProduct = "any"

AnyProduct is the value for any product.

View Source
const LanguageNone = "none"

LanguageNone is the language condition's value for contacts with no language.

View Source
const MaxSQLLength = 20000

MaxSQLLength bounds user-written SQL.

Variables

View Source
var (
	// ErrSQLDisabled means the database has no reputecast_segments role or
	// runner function (managed Postgres without CREATEROLE).
	ErrSQLDisabled = errors.New("SQL segments are turned off on this database. An admin can enable them by running: CREATE ROLE reputecast_segments NOLOGIN; GRANT reputecast_segments TO <app user>; then reputecast migrate up")
	// ErrTimeout means the query hit the statement timeout.
	ErrTimeout = errors.New("count timed out")
)

Errors returned for user-written SQL.

View Source
var ViewNames = []string{"contacts", "list_members", "events", "lists", "paid_members", "paid_tiers", "purchases"}

ViewNames are the relations a SQL segment may read.

Functions

func CheckSQL

func CheckSQL(src string) (string, error)

CheckSQL validates the shape of user-written SQL before it reaches the database: one statement, starting with SELECT or WITH. It returns the statement without a trailing semicolon.

func ImporterName

func ImporterName(k string) string

ImporterName is the tool or file kind an import came from ("Brevo", "CSV"), as SourceLabel names it; "" for a file of unknown kind.

func Problem

func Problem(ctx context.Context, err error) error

Problem turns segment errors into API problems, in the request's language.

func Register

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

Register adds the segments operations.

func RegisterFieldOptions

func RegisterFieldOptions(field string, f func(context.Context, *store.Queries, uuid.UUID) ([]SegmentOption, error))

RegisterFieldOptions sets how the catalog lists a field's values (the growth package lists the sources contacts joined through).

func SourceLabel

func SourceLabel(src string) string

SourceLabel is SourceLabelIn in English, for exports (CSV columns are data) and callers that write for API clients.

func SourceLabelIn

func SourceLabelIn(l i18n.Lang, src string) string

SourceLabelIn turns a contact source key into words in a reader's language: "import:brevo" → "Brevo import", "form:docs" → "Signup form · docs", "form:popup" → "Popup form", "api" → "API".

Types

type Compiled

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

Compiled is a builder segment rendered to SQL.

func Compile

func Compile(d SegmentDefinition, workspaceID uuid.UUID, custom map[string]CustomField) Compiled

Compile turns a validated definition into SQL over the segment views. The workspace is always the first bound value.

func (Compiled) Display

func (c Compiled) Display() string

Display is the SQL shown under "Generated SQL", values inlined.

func (Compiled) Query

func (c Compiled) Query(first int) (string, []any)

Query returns the SQL with bind parameters numbered from first.

type CustomField

type CustomField struct {
	Key   string
	Label string
	Type  string // text, number, date, boolean, select
}

CustomField is the part of a custom field definition the compiler needs.

type FieldKind

type FieldKind string

FieldKind says how a field's value is entered.

const (
	KindEnum     FieldKind = "enum"     // fixed options
	KindList     FieldKind = "list"     // a list id
	KindCampaign FieldKind = "campaign" // a campaign id
	KindText     FieldKind = "text"
	KindNumber   FieldKind = "number"
	KindDate     FieldKind = "date"
	KindBoolean  FieldKind = "boolean"
	KindPeriod   FieldKind = "period" // in the last N days/weeks
)

Field kinds.

type SQLError

type SQLError struct {
	Message  string
	Position int // 1-based character position in the user's SQL, 0 when unknown
	// contains filtered or unexported fields
}

SQLError explains why user-written SQL was refused or failed, in words the person can act on. Message is the English; Text writes ReputeCast's own explanations in a reader's language (Postgres's own errors stay as Postgres wrote them).

func (*SQLError) Error

func (e *SQLError) Error() string

func (*SQLError) Text

func (e *SQLError) Text(l i18n.Lang) string

Text is the explanation in a reader's language.

type SQLRunner

type SQLRunner struct {
	Pool    *pgxpool.Pool
	Timeout time.Duration
	// contains filtered or unexported fields
}

SQLRunner executes user-written SQL in the restricted sandbox.

func (*SQLRunner) Available

func (r *SQLRunner) Available(ctx context.Context) bool

Available reports whether the database has the runner function.

func (*SQLRunner) Run

func (r *SQLRunner) Run(ctx context.Context, ws uuid.UUID, fn func(pgx.Tx) error) error

Run executes fn in a READ ONLY transaction where the segment views exist for workspace ws and reputecast_sql.segment_ids can read them. Everything is rolled back. fn should select from reputecast_sql.segment_ids($n).

type SegmentCatalog

type SegmentCatalog struct {
	Fields []SegmentCatalogField `json:"fields"`
	// SQLEnabled is false when the database can't run SQL segments.
	SQLEnabled bool `json:"sqlEnabled"`
	// Views documents what SQL segments can read.
	Views []string `json:"views"`
}

SegmentCatalog describes everything the builder can offer.

type SegmentCatalogField

type SegmentCatalogField struct {
	Key   string            `json:"key"`
	Label string            `json:"label"`
	Kind  string            `json:"kind" enum:"enum,list,campaign,text,number,date,boolean,period"`
	Ops   []SegmentOperator `json:"ops"`
	// Options are the values of enum, list and campaign fields.
	Options []SegmentOption `json:"options"`
}

SegmentCatalogField is a field the builder can filter on.

type SegmentCondition

type SegmentCondition struct {
	// Field is a key from the catalog: mailbox_provider, email_domain, list,
	// tier, consent, source, tag, country, last_open, opened, clicked,
	// opened_campaign, joined or custom:<key>.
	Field string `json:"field" maxLength:"80"`
	Op    string `json:"op" maxLength:"20"`
	// Value is the compared value (list or campaign id, provider key, text, number, date).
	Value string `json:"value,omitempty" maxLength:"500"`
	// Amount and Unit are used by "in the last N days/weeks".
	Amount int    `json:"amount,omitempty" minimum:"0" maximum:"3650"`
	Unit   string `json:"unit,omitempty" enum:"days,weeks"`
	// To ends a range ("Score is between Value and To").
	To string `json:"to,omitempty" maxLength:"20"`
}

SegmentCondition is one row of the builder: field, operator and value.

type SegmentCountResult

type SegmentCountResult struct {
	Count int64          `json:"count"`
	Total int64          `json:"total" doc:"Contacts in the workspace"`
	Tiers SegmentTierMix `json:"tiers"`
	Ms    int64          `json:"ms" doc:"How long the count took"`
	// GeneratedSQL is the builder's SQL with values inlined (builder mode).
	GeneratedSQL string `json:"generatedSql"`
	// Cached: the same definition was counted within the last minute and
	// nothing this instance did has changed the audience since (review
	// 2026-11 OP-12). Ms is that count's time.
	Cached bool `json:"cached,omitempty"`
}

SegmentCountResult is a live count.

type SegmentDefinition

type SegmentDefinition struct {
	Groups []SegmentGroup `json:"groups"`
}

SegmentDefinition is a builder segment: groups combine with AND; inside a group the conditions match ALL or ANY.

func (SegmentDefinition) Validate

func (d SegmentDefinition) Validate(custom map[string]CustomField, lists map[uuid.UUID]string) error

Validate checks every condition against the catalog. custom maps custom field keys to their definition; lists holds the workspace's list ids.

type SegmentDetail

type SegmentDetail struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Mode        string `json:"mode" enum:"builder,sql"`
	Refresh     string `json:"refresh" enum:"dynamic,static"`
	// Definition is the builder's groups (builder mode).
	Definition SegmentDefinition `json:"definition,omitempty" required:"false"`
	// SQL is the person's own SQL (SQL mode).
	SQL string `json:"sql"`
	// GeneratedSQL is the builder's SQL with values inlined.
	GeneratedSQL string         `json:"generatedSql"`
	Count        *int64         `json:"count,omitempty"`
	CountedAt    *time.Time     `json:"countedAt,omitempty"`
	CountMs      *int32         `json:"countMs,omitempty"`
	Tiers        SegmentTierMix `json:"tiers"`
	UpdatedAt    time.Time      `json:"updatedAt"`
	UpdatedBy    string         `json:"updatedBy"`
}

SegmentDetail is one segment for the builder.

type SegmentGroup

type SegmentGroup struct {
	Match      string             `json:"match" enum:"all,any" doc:"all = every condition, any = at least one"`
	Conditions []SegmentCondition `json:"conditions"`
}

SegmentGroup is one box of conditions in the builder.

type SegmentImpact

type SegmentImpact struct {
	ID   string           `json:"id"`
	Name string           `json:"name"`
	Uses []dependents.Use `json:"uses"`
}

SegmentImpact is what deleting a segment would affect: campaigns and digests sending to it, automations using it, saved views and other segments built on it.

type SegmentInput

type SegmentInput struct {
	// Name is required to save; a preview doesn't need one.
	Name        string `json:"name,omitempty" maxLength:"120"`
	Description string `json:"description,omitempty" maxLength:"500"`
	Mode        string `json:"mode" enum:"builder,sql"`
	Refresh     string `json:"refresh,omitempty" enum:"dynamic,static"`
	// Definition is the builder's groups; SQL mode leaves it out.
	Definition SegmentDefinition `json:"definition,omitempty" required:"false"`
	SQL        string            `json:"sql,omitempty" maxLength:"20000"`
}

SegmentInput is what the builder saves or counts.

type SegmentList

type SegmentList struct {
	Items []SegmentListItem `json:"items"`
}

SegmentList is the saved segments of a workspace.

type SegmentListItem

type SegmentListItem struct {
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	Mode      string     `json:"mode" enum:"builder,sql"`
	Refresh   string     `json:"refresh" enum:"dynamic,static"`
	Count     *int64     `json:"count,omitempty" doc:"Last known count"`
	CountedAt *time.Time `json:"countedAt,omitempty"`
	UpdatedAt time.Time  `json:"updatedAt"`
}

SegmentListItem is one saved segment.

type SegmentOperator

type SegmentOperator struct {
	Key   string `json:"key"`
	Label string `json:"label"`
}

SegmentOperator is an operator a field supports.

type SegmentOption

type SegmentOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

SegmentOption is a value a condition can take.

type SegmentPathInput

type SegmentPathInput struct {
	api.WorkspaceInput
	ID string `path:"segment" format:"uuid" doc:"Segment id"`
}

type SegmentTierMix

type SegmentTierMix struct {
	Active  int64 `json:"active"`
	Cooling int64 `json:"cooling"`
	AtRisk  int64 `json:"atRisk"`
	Sunset  int64 `json:"sunset"`
}

SegmentTierMix splits a count by engagement tier.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	SQL   *SQLRunner
	// Counts keeps previews' counts for a minute (review 2026-11 OP-12);
	// nil counts every time.
	Counts *countcache.Cache
	// CountTimeout bounds builder counts (SQL mode uses SQL.Timeout).
	CountTimeout time.Duration
	Now          func() time.Time
}

func (*Service) Catalog

func (s *Service) Catalog(ctx context.Context, ws *store.Workspace) (SegmentCatalog, error)

Catalog returns the fields, operators and values for the builder, in English: the AI assistant's condition schema reads it.

func (*Service) CatalogIn

func (s *Service) CatalogIn(ctx context.Context, ws *store.Workspace, l i18n.Lang) (SegmentCatalog, error)

CatalogIn returns the catalog in a reader's language. Option lists other packages register get a context in that language (i18n.LangFrom).

func (*Service) CheckDefinition

func (s *Service) CheckDefinition(ctx context.Context, workspaceID uuid.UUID, d *SegmentDefinition) (map[string]CustomField, error)

CheckDefinition validates a builder definition and returns the custom fields Compile needs.

func (*Service) Condition

func (s *Service) Condition(ctx context.Context, workspaceID, segmentID uuid.UUID, first int) (string, []any, error)

Condition is a saved segment as a condition on contacts aliased c, for a query whose $1 is the workspace, its own placeholders numbered from first: the snapshot for a static segment, the rules as a subquery for a dynamic one, so its members never travel through Go (review 2026-11 AU-3). A SQL segment, which runs as its own restricted role, is evaluated first and comes back as ids.

func (*Service) ContactIDs

func (s *Service) ContactIDs(ctx context.Context, workspaceID, segmentID uuid.UUID) ([]uuid.UUID, error)

ContactIDs resolves a saved segment to contact ids: the snapshot for static segments, a fresh evaluation for dynamic ones. The send pipeline still excludes suppressed and role addresses on its own.

func (*Service) Create

func (s *Service) Create(ctx context.Context, ws *store.Workspace, actor *uuid.UUID, in SegmentInput) (SegmentDetail, error)

Create saves a new segment and counts it.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ws *store.Workspace, id uuid.UUID) error

func (*Service) Get

func (s *Service) Get(ctx context.Context, ws *store.Workspace, id uuid.UUID) (SegmentDetail, error)

func (*Service) HasContact

func (s *Service) HasContact(ctx context.Context, workspaceID, segmentID, contactID uuid.UUID) (bool, error)

HasContact reports whether a contact is in a segment.

func (*Service) Impact

func (s *Service) Impact(ctx context.Context, ws *store.Workspace, id uuid.UUID) (SegmentImpact, error)

Impact lists what uses a segment.

func (*Service) List

func (s *Service) List(ctx context.Context, ws *store.Workspace) (SegmentList, error)

List returns the saved segments with their last counts.

func (*Service) Preview

Preview counts an unsaved definition or SQL.

func (*Service) Recount

func (s *Service) Recount(ctx context.Context, ws *store.Workspace, id uuid.UUID) (SegmentCountResult, error)

Recount counts a saved segment and stores the result.

func (*Service) RecountAll

func (s *Service) RecountAll(ctx context.Context, ws *store.Workspace) error

RecountAll refreshes the stored count of every dynamic segment of a workspace (the nightly job). Counts that time out keep their last value.

func (*Service) Update

func (s *Service) Update(ctx context.Context, ws *store.Workspace, actor *uuid.UUID, id uuid.UUID, in SegmentInput) (SegmentDetail, error)

Update changes a segment and recounts it.

type ValidationError

type ValidationError struct {
	Location string
	Message  string
	// contains filtered or unexported fields
}

ValidationError explains which condition is wrong, for a 422. Message is the English; Text writes it in a reader's language.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Text

func (e *ValidationError) Text(l i18n.Lang) string

Text is the problem in a reader's language.

Jump to

Keyboard shortcuts

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