tracker

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: AGPL-3.0 Imports: 51 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

Package tracker is the site tracker (M62 G-28): a small script, /track/v1/rc.js, that a publisher adds to their own sites and stores (never ReputeCast's pages, which stay cookie-less), the endpoint its events go to, who a visitor is (only ever from a signed click token, a form signup's signed token or a signed identify call), the sites' settings, the contact timeline's lines, two segment conditions' data and the retention.

GET  /track/v1/rc.js                 the script, for every site
POST /p/{ws}/track/{site}/e          a site's events (and OPTIONS)

Events go through a group-commit writer (writer.go): a request is answered as soon as its events are queued, and a batch of them is written every 200 ms or 500 events in one transaction.

Index

Constants

View Source
const (
	// MaxBody is the largest request body.
	MaxBody = 8 << 10
	// MaxEvents is the most events one request carries.
	MaxEvents = 20
)

Limits of the collect endpoint.

View Source
const (
	KindPage    int16 = 1
	KindProduct int16 = 2
	KindCart    int16 = 3
	KindCustom  int16 = 4
)

Event kinds (tracker_events.kind).

View Source
const (
	ByClick    = "click"
	ByForm     = "form"
	ByIdentify = "identify"
)

Who a visitor was linked by (tracker_visitors.identified_by).

View Source
const (
	// EventDays is how long events are kept (or the workspace's event
	// detail retention when it is 30 days).
	EventDays = 90
	// BackfillDays is how much of a visitor's past joins the contact they
	// are linked to.
	BackfillDays = 30
	// AnonymousDays: a visitor never linked to a contact goes this long
	// after they were last seen, with their events.
	AnonymousDays = 30
	// InterestDays: a contact's interest in a product goes this long after
	// the last view or add-to-cart.
	InterestDays = 180
	// RefusalDays: refused origins are counted this long.
	RefusalDays = 7
)

Retention.

View Source
const BrowseBatch = 500

BrowseBatch is how many contacts one transaction takes.

View Source
const LinkKind linktoken.Kind = 232

LinkKind is the token a form signup hands to the tracker on the same page (reputecast('link', …)): its contact, valid ten minutes (linktoken.UntilMinute in Link).

View Source
const LinkValid = 10 * time.Minute

LinkValid is how long a form signup's link token works.

Variables

View Source
var Events = db.MonthlyTable{Name: "tracker_events", Key: "occurred_at", Ahead: 2, Adopt: true}

Events is tracker_events as a monthly table. Rows its default partition holds for a month (the job didn't run for months) move into the month when it is made, so a month's rows never stay there.

Functions

func Erasure

func Erasure() erasure.Source

Erasure is what the site tracker knows of a contact: the browsers linked to them, their events (with the anonymous ones of those browsers), their product interest, the store flows they entered and their "email me when it's back" requests. A visitor's own products go with it.

func FormLink(signer *linktoken.Signer, workspace, contact uuid.UUID, now time.Time) string

FormLink is the token a form signup's answer carries for the tracker on the same page: the contact, for ten minutes.

func ParseOrigin

func ParseOrigin(raw string, local bool) (origin, host string, ok bool)

ParseOrigin reads a site's address ("shop.acme.io", "https://shop.acme.io/products") as an origin: https, a host and maybe a port. http is accepted only for localhost, and only when local is true (development).

func Register

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

Register adds the Website tracking operations.

func RegisterFlowJobs

func RegisterFlowJobs(reg *jobs.Registry, f *Flows)

RegisterFlowJobs adds tracker.tick, every minute.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service)

RegisterJobs adds the retention job (hourly, and at start so the coming months exist).

func Script

func Script() []byte

Script is rc.js.

func Signature

func Signature(secret, email string) string

Signature is what a site's server sends with reputecast('identify'): hex(HMAC-SHA256(secret, lower(email))).

func VisitorHash

func VisitorHash(ws uuid.UUID, vid string) (hash []byte, ok bool)

VisitorHash is how a browser's tracker id (the rc_vid cookie) is stored, for other packages that look a visitor up (form targeting by segment, M62 G-32). ok is false for a value that isn't a tracker id.

Types

type CatalogFacts

type CatalogFacts struct {
	Sites       int64
	EventsToday int64
	LastEventAt *time.Time
	Line        string
}

CatalogFacts are the Website tracking card's facts in Settings › Integrations: the live sites, their events today and the last one, and the fact line in the reader's language ("2 sites · 1,284 events today").

type Flows

type Flows struct {
	Pool *pgxpool.Pool
	Q    *store.Queries
	Now  func() time.Time
	// Kick wakes the automations engine once events were queued.
	Kick func(ctx context.Context)
	Log  *slog.Logger
}

Browse abandonment and added to cart (M62, G-29; spec publish-sell §3.6a). Every minute, while a live flow starts on "Viewed a product and didn't buy" or "Added to cart and didn't check out", tracker.tick finds for each such flow the contacts whose last view (or add-to-cart) of the store's products happened AfterHours ago, in a window of an hour so a late or skipped minute misses no one: products in the trigger's collections, viewed MinViews times or more, nothing since on the store's products, no order and no checkout in the store since, the contact active and not erased, and not taken by the flow in the last 7 days (tracker_trigger_entries). Each one gets an automation event naming the flow (automations/storeflows.go), with the products they looked at in the day before: the store block "Viewed products" shows them, and {{ browse.products }} lists them (title, url, image, price).

Flows is independent of the collect side (Service): it reads only tracker_product_views, the per-contact interest the collect writer keeps.

func (*Flows) Tick

func (f *Flows) Tick(ctx context.Context) (int, error)

Tick is one minute's work: it returns how many contacts entered a flow. Nothing is read unless a live flow listens.

type RetentionArgs

type RetentionArgs struct{}

RetentionArgs runs the retention (hourly).

func (RetentionArgs) InsertOpts

func (RetentionArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (RetentionArgs) Kind

func (RetentionArgs) Kind() string

Kind implements river.JobArgs.

type RetentionResult

type RetentionResult struct {
	Made, Dropped                         []string
	Events, Visitors, Interests, Refusals int64
}

RetentionResult says what a run did.

type RetentionWorker

type RetentionWorker struct {
	river.WorkerDefaults[RetentionArgs]
	S *Service
}

RetentionWorker runs RetentionArgs.

func (*RetentionWorker) Work

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Links *linktoken.Signer
	URLs  publicurl.Builder
	Log   *slog.Logger
	Now   func() time.Time
	// Hosts are the hosts workspaces hold (custom domains, the publication
	// website): ReputeCast's own pages, which are never tracked.
	Hosts *customhost.Hosts
	// Carries reports whether the host a request came to may carry the
	// workspace's endpoints (customhost.Hosts.CarriesSlug); nil carries
	// every workspace's.
	Carries func(r *http.Request, slug string) bool
	// Development allows http://localhost origins.
	Development func() bool
	// Writers is how many batches are written at once (default 2).
	Writers int
	// contains filtered or unexported fields
}

Service is the site tracker.

func (*Service) Catalog

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

Catalog reads the card's facts.

func (*Service) Close

func (s *Service) Close(ctx context.Context) error

Close waits until the events queued so far are written (tests, and a process that stops).

func (*Service) ContactActivity

func (s *Service) ContactActivity(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, before *time.Time, beforeID string, limit int) ([]audience.ContactActivityItem, int64, error)

ContactActivity implements audience.ActivitySource: a line per day (in the workspace's time zone) and site the contact was on it, "Viewed 3 products on shop.acme.io" or "Visited shop.acme.io", newest first.

func (*Service) CreateSite

CreateSite adds a site with a new identify secret, returned once.

func (*Service) Decorate

func (s *Service) Decorate(ctx context.Context, c tracking.ClickedLink) string

Decorate implements tracking.LinkDecorator.

func (*Service) DeleteSite

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

DeleteSite stops a site's tracking at once; its events go with the retention.

func (*Service) RecentEvents

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

RecentEvents are a site's last 20 events of the last day.

func (*Service) Retain

func (s *Service) Retain(ctx context.Context) (RetentionResult, error)

Retain runs the retention once.

func (*Service) RotateSecret

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

RotateSecret gives a site a new identify secret, returned once; the old one stops working at once.

func (*Service) Routes

func (s *Service) Routes(r chi.Router)

Routes mounts the script and the collect endpoint.

func (*Service) Site

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

Site reads one site.

func (*Service) Sites

Sites lists the workspace's sites.

func (*Service) UpdateSite

func (s *Service) UpdateSite(ctx context.Context, ws *store.Workspace, id uuid.UUID, in TrackerSiteUpdate) (TrackerSite, error)

UpdateSite changes a site's name, store and consent mode.

func (*Service) WriterStats

func (s *Service) WriterStats() WriterStats

WriterStats reports the writer's counts.

type TickArgs

type TickArgs struct{}

TickArgs runs every minute.

func (TickArgs) InsertOpts

func (TickArgs) InsertOpts() river.InsertOpts

InsertOpts: one tick at a time.

func (TickArgs) Kind

func (TickArgs) Kind() string

Kind implements river.JobArgs.

type TickWorker

type TickWorker struct {
	river.WorkerDefaults[TickArgs]
	F *Flows
}

TickWorker finds who enters the browse and cart flows.

func (*TickWorker) Work

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

Work implements river.Worker.

type TrackerRecentEvent

type TrackerRecentEvent struct {
	Kind         string    `json:"kind" enum:"page,product,cart,custom"`
	Path         string    `json:"path"`
	ProductTitle string    `json:"productTitle"`
	Name         string    `json:"name"`
	Known        bool      `json:"known" doc:"A known contact's, else a visitor's"`
	At           time.Time `json:"at"`
}

TrackerRecentEvent is one of a site's last events (never an address).

type TrackerRecentEvents

type TrackerRecentEvents struct {
	Items []TrackerRecentEvent `json:"items"`
}

TrackerRecentEvents is the setup's live check.

type TrackerRefusal

type TrackerRefusal struct {
	Origin string    `json:"origin"`
	Count  int64     `json:"count"`
	LastAt time.Time `json:"lastAt"`
}

TrackerRefusal is an origin whose events a site refused (another site using its snippet), in the last 24 hours.

type TrackerSecret

type TrackerSecret struct {
	IdentifySecret string `json:"identifySecret"`
}

TrackerSecret is a site's new identify secret, shown once.

type TrackerSite

type TrackerSite struct {
	ID          string              `json:"id" format:"uuid"`
	Name        string              `json:"name"`
	Origin      string              `json:"origin" example:"https://shop.acme.io"`
	Store       *TrackerStoreOption `json:"store,omitempty"`
	WaitConsent bool                `json:"waitConsent"`
	// HasIdentifySecret: the site has a secret to sign identify calls with
	// (never returned but by create and rotate).
	HasIdentifySecret bool  `json:"hasIdentifySecret"`
	EventsToday       int64 `json:"eventsToday" doc:"Events since midnight in the workspace's time zone"`
	// CreatedBy is the name of the member who added the site ("" once
	// they left).
	CreatedBy   string           `json:"createdBy"`
	LastEventAt *time.Time       `json:"lastEventAt,omitempty"`
	CreatedAt   time.Time        `json:"createdAt"`
	Refused     []TrackerRefusal `json:"refused" doc:"Origins refused in the last 24 hours, most refused first"`
	Snippet     TrackerSnippet   `json:"snippet"`
}

TrackerSite is a tracked site.

type TrackerSiteCreated

type TrackerSiteCreated struct {
	Site           TrackerSite `json:"site"`
	IdentifySecret string      `json:"identifySecret" doc:"Shown once: the site's server signs identify calls with it"`
}

TrackerSiteCreated is a new site, with its identify secret, shown once.

type TrackerSiteInput

type TrackerSiteInput struct {
	Name string `json:"name" maxLength:"200"`
	// Origin is the site's address: "shop.acme.io" or "https://shop.acme.io".
	Origin      string `json:"origin" maxLength:"300"`
	StoreID     string `json:"storeId,omitempty" maxLength:"40"`
	WaitConsent bool   `json:"waitConsent" doc:"Nothing is stored until the site's consent banner calls reputecast('consent', true)"`
}

TrackerSiteInput adds a site.

type TrackerSiteList

type TrackerSiteList struct {
	Items []TrackerSite `json:"items"`
	// Stores are the connected stores a site can be linked to.
	Stores    []TrackerStoreOption `json:"stores"`
	ScriptURL string               `json:"scriptUrl"`
	// CanManage: the caller holds integrations:manage; Helpers are up to
	// two members who do (a Viewer's "Ask Marcus Chen or Linh Nguyen.").
	CanManage bool     `json:"canManage"`
	Helpers   []string `json:"helpers"`
}

TrackerSiteList is the Website tracking page.

type TrackerSitePath

type TrackerSitePath struct {
	api.WorkspaceInput
	Site string `path:"site" format:"uuid" doc:"Tracked site id"`
}

TrackerSitePath names a tracked site.

type TrackerSiteUpdate

type TrackerSiteUpdate struct {
	Name        string `json:"name" maxLength:"200"`
	StoreID     string `json:"storeId,omitempty" maxLength:"40"`
	WaitConsent bool   `json:"waitConsent"`
}

TrackerSiteUpdate changes a site; its origin stays.

type TrackerSnippet

type TrackerSnippet struct {
	Script       string `json:"script"`
	ShopifyPixel string `json:"shopifyPixel"`
	WordPress    string `json:"wordpress"`
}

TrackerSnippet is what a site adds: the script tag, the Shopify custom pixel's code, and the WordPress plugin's setting.

type TrackerStoreOption

type TrackerStoreOption struct {
	ID       string `json:"id" format:"uuid"`
	Name     string `json:"name"`
	Platform string `json:"platform" enum:"shopify,woocommerce"`
}

TrackerStoreOption is a connected store a site can be linked to.

type WriterStats

type WriterStats struct {
	Written, Dropped int64
}

WriterStats are the events the writer wrote and dropped since the process started.

Jump to

Keyboard shortcuts

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