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
- Variables
- func CheckSQL(src string) (string, error)
- func ImporterName(k string) string
- func Problem(ctx context.Context, err error) error
- func Register(h huma.API, s *Service)
- func RegisterFieldOptions(field string, ...)
- func SourceLabel(src string) string
- func SourceLabelIn(l i18n.Lang, src string) string
- type Compiled
- type CustomField
- type FieldKind
- type SQLError
- type SQLRunner
- type SegmentCatalog
- type SegmentCatalogField
- type SegmentCondition
- type SegmentCountResult
- type SegmentDefinition
- type SegmentDetail
- type SegmentGroup
- type SegmentInput
- type SegmentList
- type SegmentListItem
- type SegmentOperator
- type SegmentOption
- type SegmentPathInput
- type SegmentTierMix
- type Service
- func (s *Service) Catalog(ctx context.Context, ws *store.Workspace) (SegmentCatalog, error)
- func (s *Service) CatalogIn(ctx context.Context, ws *store.Workspace, l i18n.Lang) (SegmentCatalog, error)
- func (s *Service) CheckDefinition(ctx context.Context, workspaceID uuid.UUID, d *SegmentDefinition) (map[string]CustomField, error)
- func (s *Service) ContactIDs(ctx context.Context, workspaceID, segmentID uuid.UUID) ([]uuid.UUID, error)
- func (s *Service) Create(ctx context.Context, ws *store.Workspace, actor *uuid.UUID, in SegmentInput) (SegmentDetail, error)
- func (s *Service) Delete(ctx context.Context, ws *store.Workspace, id uuid.UUID) error
- func (s *Service) Get(ctx context.Context, ws *store.Workspace, id uuid.UUID) (SegmentDetail, error)
- func (s *Service) HasContact(ctx context.Context, workspaceID, segmentID, contactID uuid.UUID) (bool, error)
- func (s *Service) List(ctx context.Context, ws *store.Workspace) (SegmentList, error)
- func (s *Service) Preview(ctx context.Context, ws *store.Workspace, in SegmentInput) (SegmentCountResult, error)
- func (s *Service) Recount(ctx context.Context, ws *store.Workspace, id uuid.UUID) (SegmentCountResult, error)
- func (s *Service) RecountAll(ctx context.Context, ws *store.Workspace) error
- func (s *Service) Update(ctx context.Context, ws *store.Workspace, actor *uuid.UUID, id uuid.UUID, ...) (SegmentDetail, error)
- type ValidationError
Constants ¶
const ( CodeSQLError = "sql_error" CodeSQLDisabled = "sql_disabled" CodeTimeout = "count_timeout" )
Problem codes of this package.
const ( FieldPaidStatus = "paid_status" FieldPaidTier = "paid_tier" FieldPaidPeriod = "paid_period" FieldPaidSince = "paid_since" FieldPaidEnded = "paid_ended" FieldPaidLTV = "paid_ltv" )
The paid subscription fields.
const ( FieldPushSite = "push_site" FieldPushBrowser = "push_browser" FieldWhatsAppConsent = "whatsapp_consent" )
The push and WhatsApp fields.
const AnyProduct = "any"
AnyProduct is the value for any product.
const LanguageNone = "none"
LanguageNone is the language condition's value for contacts with no language.
const MaxSQLLength = 20000
MaxSQLLength bounds user-written SQL.
Variables ¶
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.
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 ¶
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 ¶
ImporterName is the tool or file kind an import came from ("Brevo", "CSV"), as SourceLabel names it; "" for a file of unknown kind.
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 ¶
SourceLabel is SourceLabelIn in English, for exports (CSV columns are data) and callers that write for API clients.
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.
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).
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.
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"`
}
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 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 ¶
SegmentOperator is an operator a field supports.
type SegmentOption ¶
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
// CountTimeout bounds builder counts (SQL mode uses SQL.Timeout).
CountTimeout time.Duration
Now func() time.Time
}
func (*Service) Catalog ¶
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) 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) 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) Preview ¶
func (s *Service) Preview(ctx context.Context, ws *store.Workspace, in SegmentInput) (SegmentCountResult, error)
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 ¶
RecountAll refreshes the stored count of every dynamic segment of a workspace (the nightly job). Counts that time out keep their last value.
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