Documentation
¶
Index ¶
- Constants
- func BotPathPatterns() []string
- func IsBot(userAgent string) bool
- func IsBotPath(path string) bool
- func IsDataCenterIP(ip string) bool
- func IsMaliciousPath(path string) bool
- func IsReferrerSpam(referrer string) bool
- func MaliciousPathPatterns() []string
- type DefaultGeoIPResolver
- type GeoIPResolver
- type NewStoreOptions
- type SessionInterface
- type StoreInterface
- type UserAgentInfo
- type VisitorInterface
- type VisitorQueryInterface
Constants ¶
const ( COLUMN_ID = "id" COLUMN_COUNTRY = "country" COLUMN_CREATED_AT = "created_at" COLUMN_SOFT_DELETED_AT = "soft_deleted_at" COLUMN_IP_ADDRESS = "ip_address" COLUMN_PATH = "path" COLUMN_UPDATED_AT = "updated_at" COLUMN_FINGERPRINT = "fingerprint" COLUMN_USER_AGENT = "user_agent" COLUMN_USER_ACCEPT_LANGUAGE = "user_accept_language" COLUMN_USER_ACCEPT_ENCODING = "user_accept_encoding" COLUMN_USER_BROWSER = "user_browser" COLUMN_USER_BROWSER_VERSION = "user_browser_version" COLUMN_USER_DEVICE = "user_device" COLUMN_USER_DEVICE_TYPE = "user_device_type" COLUMN_USER_OS = "user_os" COLUMN_USER_OS_VERSION = "user_os_version" COLUMN_USER_REFERRER = "user_referrer" COLUMN_BOT = "bot" COLUMN_THREAT = "threat" COLUMN_SESSION_ID = "session_id" COLUMN_UTM_SOURCE = "utm_source" COLUMN_UTM_MEDIUM = "utm_medium" COLUMN_UTM_CAMPAIGN = "utm_campaign" COLUMN_UTM_TERM = "utm_term" COLUMN_UTM_CONTENT = "utm_content" COLUMN_REFERRER_HOST = "referrer_host" )
const ( VALUE_YES = "yes" VALUE_NO = "no" )
Yes/No string values used for boolean-like columns (bot, threat). Stored as VARCHAR(3) to match the existing all-string column convention.
const ( COLUMN_KEY = "key" COLUMN_VALUE = "value" SETTING_EXCLUDED_IPS = "excluded_ips" SETTING_EXCLUDED_PATHS = "excluded_paths" SETTING_INCLUDED_PATHS = "included_paths" )
Settings table column names.
const ( MAX_LEN_ID = 40 MAX_LEN_PATH = 510 MAX_LEN_FINGERPRINT = 40 MAX_LEN_IP_ADDRESS = 40 MAX_LEN_COUNTRY = 2 MAX_LEN_USER_ACCEPT_LANGUAGE = 100 MAX_LEN_USER_ACCEPT_ENCODING = 40 MAX_LEN_USER_AGENT = 510 MAX_LEN_USER_OS = 50 MAX_LEN_USER_OS_VERSION = 50 MAX_LEN_USER_DEVICE = 100 MAX_LEN_USER_DEVICE_TYPE = 50 MAX_LEN_USER_BROWSER = 100 MAX_LEN_USER_BROWSER_VERSION = 100 MAX_LEN_USER_REFERRER = 510 MAX_LEN_BOT = 3 MAX_LEN_THREAT = 3 MAX_LEN_SESSION_ID = 40 MAX_LEN_UTM = 255 MAX_LEN_REFERRER_HOST = 255 )
Maximum column lengths for string fields.
const ( // GeoIPEndpointDefault is the default IP geolocation endpoint (ip2c.org). GeoIPEndpointDefault = "https://ip2c.org/" // GeoIPTimeoutDefault is the default timeout for IP geolocation lookups. GeoIPTimeoutDefault = 5 * time.Second // CountryUnknown is used for IPs that cannot be resolved (e.g. localhost). CountryUnknown = "UN" // GeoIPCacheTTLDefault is the default TTL for the in-memory IP cache. GeoIPCacheTTLDefault = 24 * time.Hour )
const DEFAULT_SETTINGS_TABLE = "statsstore_settings"
Default table name for key-value settings.
const MAX_DATETIME = "9999-12-31 23:59:59"
MAX_DATETIME is a far-future datetime used as the default soft-delete sentinel.
const SESSION_GAP_MINUTES = 30
SESSION_GAP_MINUTES is the maximum gap between consecutive page views that keeps them in the same session. A view arriving more than this many minutes after the fingerprint's previous view starts a new session.
const VisitorCreateAsyncBufferSizeDefault = 4096
VisitorCreateAsyncBufferSizeDefault bounds the pending-insert queue when VisitorCreateAsyncEnabled is set. Sized so a burst of requests cannot exhaust memory; when full, new visitor rows are dropped rather than blocking the request path on a database write.
Variables ¶
This section is empty.
Functions ¶
func BotPathPatterns ¶ added in v1.22.0
func BotPathPatterns() []string
BotPathPatterns returns the list of path substrings for bot-only files (robots.txt, ads.txt, sitemap.xml, etc.).
func IsBot ¶ added in v1.8.0
IsBot checks whether a user-agent string belongs to a bot, crawler, or automated tool. An empty user-agent returns false.
func IsDataCenterIP ¶ added in v1.8.0
IsDataCenterIP checks whether an IP address falls within known data center CIDR ranges.
func IsMaliciousPath ¶ added in v1.22.0
IsMaliciousPath reports whether a request path targets a universally malicious endpoint.
func IsReferrerSpam ¶ added in v1.8.0
IsReferrerSpam checks whether a referrer URL host matches a known spam domain.
func MaliciousPathPatterns ¶ added in v1.22.0
func MaliciousPathPatterns() []string
MaliciousPathPatterns returns the list of path substrings for universally malicious endpoints (.env, .git/, .svn/, .htpasswd, shell.php).
Types ¶
type DefaultGeoIPResolver ¶ added in v1.11.0
type DefaultGeoIPResolver struct {
Endpoint string // default: GeoIPEndpointDefault
Timeout time.Duration // default: GeoIPTimeoutDefault
HTTPClient *http.Client // injectable for testing; if nil, a default client is used
CacheTTL time.Duration // default: GeoIPCacheTTLDefault; set to 0 to disable caching
// contains filtered or unexported fields
}
DefaultGeoIPResolver implements GeoIPResolver using the ip2c.org service. It includes an in-memory cache with TTL to avoid duplicate lookups for the same IP within the cache window.
func NewDefaultGeoIPResolver ¶ added in v1.11.0
func NewDefaultGeoIPResolver() *DefaultGeoIPResolver
NewDefaultGeoIPResolver creates a DefaultGeoIPResolver with sensible defaults.
type GeoIPResolver ¶ added in v1.11.0
type GeoIPResolver interface {
// Resolve returns an ISO2 country code (e.g. "US", "GB") for the given IP.
// If the IP cannot be resolved, it returns CountryUnknown and nil error.
// If the lookup itself fails (network error, bad response), it returns
// an empty string and the error so the caller can leave the field empty
// for a retry.
Resolve(ctx context.Context, ip string) (string, error)
}
GeoIPResolver resolves an IP address to an ISO 3166-1 alpha-2 country code. Implementations may use an external API, a local MaxMind database, or any other source. A nil/empty result with no error means the IP could not be resolved and the country should be left empty for a later retry.
type NewStoreOptions ¶
type NewStoreOptions struct {
VisitorTableName string
SettingsTableName string
DB *sql.DB
AutomigrateEnabled bool
DebugEnabled bool
BotFilterEnabled bool // when true, skip bot/threat traffic at ingestion (don't insert). Independent of BotAutoTagEnabled.
BotAutoTagEnabled bool // when true, compute and set bot/threat flags on inserted rows. Also auto-computes flags on VisitorCreate/VisitorUpdate.
ExcludedPathPrefixes []string
IncludedPathPrefixes []string // when non-empty, acts as a whitelist: only matching paths are tracked
ExcludedIPs []string
GeoIPResolver GeoIPResolver // optional; enables VisitorEnhance for batch country enrichment
EnhanceBatchSize int // number of records per VisitorEnhance call; default 10
// TrustedProxies lists CIDR ranges or IPs of reverse proxies whose
// forwarding headers (X-Forwarded-For, X-Real-IP) may be trusted when
// resolving the client IP in VisitorRegister. When empty, req.GetIP is
// used and forwarding headers are trusted unconditionally — only safe
// when the app runs behind a proxy that sanitizes them.
TrustedProxies []string
// FingerprintSalt is an optional secret prepended before hashing the
// visitor fingerprint (SHA-256 of IP + user agent). It makes stored
// fingerprints impossible to reverse by dictionary attack on common
// IP/UA pairs.
FingerprintSalt string
// VisitorCreateAsyncEnabled makes VisitorCreate queue the INSERT on a
// background worker instead of waiting for the database write. Use on
// request hot paths (per-request visitor tracking) where insert
// latency must not block the response. Errors are logged, not
// returned. Call DrainVisitorWrites during shutdown, before closing
// the underlying database.
VisitorCreateAsyncEnabled bool
// VisitorCreateAsyncBufferSize bounds the pending-insert queue.
// Values <= 0 use VisitorCreateAsyncBufferSizeDefault.
VisitorCreateAsyncBufferSize int
}
NewStoreOptions defines the options for creating a new stats store.
type SessionInterface ¶ added in v1.33.0
type SessionInterface interface {
GetSessionID() string
GetFingerprint() string
GetIpAddress() string
GetCountry() string
GetUserDeviceType() string
GetUserBrowser() string
GetUserOs() string
GetStartedAt() string
GetStartedAtCarbon() *carbon.Carbon
GetEndedAt() string
GetEndedAtCarbon() *carbon.Carbon
// GetDurationSeconds returns ended_at - started_at in seconds.
GetDurationSeconds() int64
GetPageViews() int64
GetBotRows() int64
GetEntryPath() string
SetEntryPath(path string) SessionInterface
GetExitPath() string
SetExitPath(path string) SessionInterface
// IsBounce reports whether the session consisted of a single page view.
IsBounce() bool
}
SessionInterface defines a visitor session: a group of page views sharing a session id (same fingerprint, consecutive views within SESSION_GAP_MINUTES).
type StoreInterface ¶
type StoreInterface interface {
// MigrateDown drops the stats store tables
MigrateDown(ctx context.Context, tx ...*sql.Tx) error
// MigrateUp creates the stats store tables
MigrateUp(ctx context.Context, tx ...*sql.Tx) error
EnableDebug(debug bool)
GetDB() *sql.DB
SetBotFilterEnabled(enabled bool)
IsBotFilterEnabled() bool
SetBotAutoTagEnabled(enabled bool)
IsBotAutoTagEnabled() bool
SetExcludedPathPrefixes(prefixes []string)
GetExcludedPathPrefixes() []string
SetIncludedPathPrefixes(prefixes []string)
GetIncludedPathPrefixes() []string
// ExcludedPathList/Add/Remove manage persisted excluded path prefixes
// (stored as a JSON array in the settings table under "excluded_paths").
// Excluded prefixes are skipped by VisitorRegister.
ExcludedPathList(ctx context.Context) ([]string, error)
ExcludedPathAdd(ctx context.Context, prefix string) error
ExcludedPathRemove(ctx context.Context, prefix string) error
// IncludedPathList/Add/Remove manage persisted included path prefixes
// (stored under "included_paths"). When non-empty they act as a
// whitelist: only matching paths are tracked by VisitorRegister.
IncludedPathList(ctx context.Context) ([]string, error)
IncludedPathAdd(ctx context.Context, prefix string) error
IncludedPathRemove(ctx context.Context, prefix string) error
SetExcludedIPs(ips []string)
GetExcludedIPs() []string
ExcludedIPList(ctx context.Context) ([]string, error)
ExcludedIPAdd(ctx context.Context, ip string) error
ExcludedIPRemove(ctx context.Context, ip string) error
// SettingGet retrieves a setting value by key. Returns empty string and
// nil error if the key does not exist.
SettingGet(ctx context.Context, key string) (string, error)
// SettingSet stores a setting value by key, using upsert semantics.
SettingSet(ctx context.Context, key, value string) error
// SettingDelete removes a setting by key. No error if the key is absent.
SettingDelete(ctx context.Context, key string) error
// SettingHas reports whether a setting key exists.
SettingHas(ctx context.Context, key string) (bool, error)
// SettingList returns all settings as a map of key to value.
// Returns an empty map if the settings table does not exist or is empty.
SettingList(ctx context.Context) (map[string]string, error)
VisitorCount(ctx context.Context, query VisitorQueryInterface) (int64, error)
VisitorCreate(ctx context.Context, user VisitorInterface) error
// DrainVisitorWrites flushes the async insert queue (when
// VisitorCreateAsyncEnabled is set) and returns after all pending
// rows are written. Safe to call when async is disabled.
DrainVisitorWrites()
// VisitorDroppedCount returns rows dropped because the async insert
// queue was full or already drained. Always 0 when async is disabled.
VisitorDroppedCount() uint64
VisitorDelete(ctx context.Context, user VisitorInterface) error
VisitorDeleteByID(ctx context.Context, id string) error
VisitorDeleteByIP(ctx context.Context, ip string) (int64, error)
// VisitorDeleteByIDs permanently deletes all visitor records with the
// given IDs in a single DELETE. Returns the number of deleted rows.
VisitorDeleteByIDs(ctx context.Context, ids []string) (int64, error)
VisitorDeleteOlderThan(ctx context.Context, timestamp string) (int64, error)
// VisitorSetBotByIP sets the bot flag on all visitor records for the
// given IP in a single UPDATE. Returns the number of updated rows.
// Valid bot values are VALUE_YES and VALUE_NO.
VisitorSetBotByIP(ctx context.Context, ip, bot string) (int64, error)
// VisitorSetThreatByIP sets the threat flag on all visitor records for
// the given IP in a single UPDATE. Returns the number of updated rows.
// Valid threat values are VALUE_YES and VALUE_NO.
VisitorSetThreatByIP(ctx context.Context, ip, threat string) (int64, error)
VisitorFindByID(ctx context.Context, userID string) (VisitorInterface, error)
VisitorList(ctx context.Context, query VisitorQueryInterface) ([]VisitorInterface, error)
VisitorRegister(ctx context.Context, r *http.Request) error
VisitorSoftDelete(ctx context.Context, user VisitorInterface) error
VisitorSoftDeleteByID(ctx context.Context, id string) error
VisitorUpdate(ctx context.Context, user VisitorInterface) error
// VisitorEnhance enriches visitor records that have an empty country field.
// It parses the user agent (browser, OS, device type) and looks up the
// country via the configured GeoIPResolver. UA fields are updated even if
// the geo-IP lookup fails; the country stays empty for retry.
// Returns the number of records fully processed (country + UA).
// Call this from a background task/cron on whatever schedule suits your
// traffic (e.g. every 5 minutes).
//
// If no GeoIPResolver was configured, it returns 0 and an error.
VisitorEnhance(ctx context.Context) (int, error)
// SessionList aggregates visitor rows into sessions (same fingerprint,
// consecutive views within SESSION_GAP_MINUTES). VisitorQuery filters
// apply to the underlying rows; limit/offset paginate sessions ordered by
// last activity. Rows predating the session_id column are excluded.
SessionList(ctx context.Context, query VisitorQueryInterface) ([]SessionInterface, error)
// SessionCount counts distinct session ids matching the visitor query.
SessionCount(ctx context.Context, query VisitorQueryInterface) (int64, error)
// SessionIDBackfill assigns session ids to legacy rows that predate the
// session_id column, oldest-first so sessions chain across the gap window.
SessionIDBackfill(ctx context.Context, query VisitorQueryInterface) (int64, error)
}
StoreInterface defines the interface for a stats store.
func NewStore ¶
func NewStore(opts NewStoreOptions) (StoreInterface, error)
NewStore creates a new stats store.
type UserAgentInfo ¶ added in v1.16.0
type UserAgentInfo = botdetect.UserAgentInfo
UserAgentInfo holds parsed user-agent data. Alias of botdetect.UserAgentInfo — all name fields are lowercase.
func ParseUserAgent ¶ added in v1.16.0
func ParseUserAgent(ua string) UserAgentInfo
ParseUserAgent extracts browser, OS, device, and device-type from a user-agent string. Delegates to botdetect.ParseUserAgent; unknown values are left as empty strings, and bots report DeviceType "bot".
type VisitorInterface ¶
type VisitorInterface interface {
// Methods
FingerprintCalculate() string
IsSoftDeleted() bool
GetID() string
SetID(id string) VisitorInterface
GetPath() string
SetPath(path string) VisitorInterface
GetCountry() string
SetCountry(country string) VisitorInterface
GetCreatedAt() string
GetCreatedAtCarbon() *carbon.Carbon
SetCreatedAt(createdAt string) VisitorInterface
GetSoftDeletedAt() string
GetSoftDeletedAtCarbon() *carbon.Carbon
SetSoftDeletedAt(deletedAt string) VisitorInterface
GetFingerprint() string
SetFingerprint(fingerprint string) VisitorInterface
GetSessionID() string
SetSessionID(sessionID string) VisitorInterface
GetUtmSource() string
SetUtmSource(utmSource string) VisitorInterface
GetUtmMedium() string
SetUtmMedium(utmMedium string) VisitorInterface
GetUtmCampaign() string
SetUtmCampaign(utmCampaign string) VisitorInterface
GetUtmTerm() string
SetUtmTerm(utmTerm string) VisitorInterface
GetUtmContent() string
SetUtmContent(utmContent string) VisitorInterface
GetReferrerHost() string
SetReferrerHost(referrerHost string) VisitorInterface
GetIpAddress() string
SetIpAddress(ipAddress string) VisitorInterface
GetUpdatedAt() string
GetUpdatedAtCarbon() *carbon.Carbon
SetUpdatedAt(updatedAt string) VisitorInterface
GetUserAcceptLanguage() string
SetUserAcceptLanguage(userAcceptLanguage string) VisitorInterface
GetUserAcceptEncoding() string
SetUserAcceptEncoding(userAcceptEncoding string) VisitorInterface
GetUserAgent() string
SetUserAgent(userAgent string) VisitorInterface
GetUserBrowser() string
SetUserBrowser(userBrowser string) VisitorInterface
GetUserBrowserVersion() string
SetUserBrowserVersion(userBrowserVersion string) VisitorInterface
GetUserDevice() string
SetUserDevice(userDevice string) VisitorInterface
GetUserDeviceType() string
SetUserDeviceType(userDeviceType string) VisitorInterface
GetUserOs() string
SetUserOs(userOs string) VisitorInterface
GetUserOsVersion() string
SetUserOsVersion(userOsVersion string) VisitorInterface
GetUserReferrer() string
SetUserReferrer(userReferrer string) VisitorInterface
GetBot() string
SetBot(bot string) VisitorInterface
GetThreat() string
SetThreat(threat string) VisitorInterface
}
VisitorInterface defines the interface for a visitor record.
func NewVisitorFromExistingData ¶
func NewVisitorFromExistingData(data map[string]string) VisitorInterface
NewVisitorFromExistingData creates a new visitor from a raw column map.
type VisitorQueryInterface ¶ added in v1.1.0
type VisitorQueryInterface interface {
Validate() error
HasCountry() bool
Country() string
SetCountry(country string) VisitorQueryInterface
HasCreatedAtGte() bool
CreatedAtGte() string
SetCreatedAtGte(createdAtGte string) VisitorQueryInterface
HasCreatedAtLte() bool
CreatedAtLte() string
SetCreatedAtLte(createdAtLte string) VisitorQueryInterface
HasDeviceType() bool
DeviceType() string
SetDeviceType(deviceType string) VisitorQueryInterface
HasDistinct() bool
Distinct() string
SetDistinct(distinct string) VisitorQueryInterface
HasID() bool
ID() string
SetID(id string) VisitorQueryInterface
HasIDIn() bool
IDIn() []string
SetIDIn(idIn []string) VisitorQueryInterface
HasIPIn() bool
IPIn() []string
SetIPIn(ipIn []string) VisitorQueryInterface
HasIPNotIn() bool
IPNotIn() []string
SetIPNotIn(ipNotIn []string) VisitorQueryInterface
HasLimit() bool
Limit() int
SetLimit(limit int) VisitorQueryInterface
HasOffset() bool
Offset() int
SetOffset(offset int) VisitorQueryInterface
HasOrderBy() bool
OrderBy() string
SetOrderBy(orderBy string) VisitorQueryInterface
HasPathContains() bool
PathContains() string
SetPathContains(pathContains string) VisitorQueryInterface
HasSessionID() bool
SessionID() string
SetSessionID(sessionID string) VisitorQueryInterface
HasUtmSource() bool
UtmSource() string
SetUtmSource(utmSource string) VisitorQueryInterface
HasUtmMedium() bool
UtmMedium() string
SetUtmMedium(utmMedium string) VisitorQueryInterface
HasUtmCampaign() bool
UtmCampaign() string
SetUtmCampaign(utmCampaign string) VisitorQueryInterface
HasUtmTerm() bool
UtmTerm() string
SetUtmTerm(utmTerm string) VisitorQueryInterface
HasUtmContent() bool
UtmContent() string
SetUtmContent(utmContent string) VisitorQueryInterface
HasReferrerHost() bool
ReferrerHost() string
SetReferrerHost(referrerHost string) VisitorQueryInterface
HasPathExact() bool
PathExact() string
SetPathExact(pathExact string) VisitorQueryInterface
HasSortOrder() bool
SortOrder() string
SetSortOrder(sortOrder string) VisitorQueryInterface
HasSoftDeletedIncluded() bool
SoftDeletedIncluded() bool
SetSoftDeletedIncluded(withSoftDeleted bool) VisitorQueryInterface
HasBot() bool
Bot() string
SetBot(bot string) VisitorQueryInterface
HasThreat() bool
Threat() string
SetThreat(threat string) VisitorQueryInterface
}
VisitorQueryInterface defines the interface for visitor query operations.
func NewVisitorQuery ¶ added in v1.1.0
func NewVisitorQuery() VisitorQueryInterface
NewVisitorQuery creates a new visitor query.
func VisitorQuery ¶ added in v1.1.0
func VisitorQuery() VisitorQueryInterface
VisitorQuery is a shortcut for NewVisitorQuery.