analytics

package
v0.4.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 22 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 analytics is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package analytics provides the NSGo-free wire contract, property validation, versioned YAML event catalog, session derivation, sinks (daily JSON Lines files and in-memory), HTTP client sink and self-hosted collector service for consented game analytics.

Client games queue events through liveops.BatchProvider and deliver gzipped JSON Lines batches to Service.Handler (run standalone by cmd/analyticsd or mounted inside pkg/online/backend). Game servers emit authoritative events (such as match results or granted purchases) through Service.Emit and update per-account custom properties through Service.UpdateProperties.

This package depends only on the Go standard library, go.yaml.in/yaml/v3 and sibling headless packages; it never imports NSGo or any SQL driver. The Postgres sink lives in pkg/online/liveops/analytics/pgstore.

Index

Examples

Constants

View Source
const (
	SourceClient = "client"
	SourceServer = "server"
)

Source values identify whether an event arrived from a game client or server code.

View Source
const (
	EventSessionStart = "session_start"
	EventSessionEnd   = "session_end"
)

Derived session lifecycle event names produced from session IDs.

View Source
const (
	DefaultMaxEventNameLength      = 64
	DefaultMaxProperties           = 32
	DefaultMaxPropertyKeyLength    = 64
	DefaultMaxPropertyStringLength = 256
	DefaultMaxEventBytes           = 16 << 10
	DefaultMaxBatchBytes           = 1 << 20
	DefaultMaxBatchEvents          = 1000
	DefaultMaxContextLength        = 128
)

Default validation caps applied by DefaultLimits.

View Source
const CatalogVersion = 1

CatalogVersion is the schema version of an analytics event catalog YAML file.

View Source
const ConfigVersion = 1

ConfigVersion is the schema version of an analytics collector config YAML file.

View Source
const DefaultAudience = "analytics"

DefaultAudience is the JWT audience the collector accepts when Config.Audience is empty.

View Source
const ProfilesVersion = 1

ProfilesVersion is the schema version of FileSink's profiles.json file.

View Source
const RecordVersion = 1

RecordVersion is the schema version written as "v" on each collector JSON Lines record.

Variables

View Source
var (
	ErrInvalidEventName     = errors.New("analytics: invalid event name")
	ErrInvalidPropertyKey   = errors.New("analytics: invalid property key")
	ErrForbiddenPropertyKey = errors.New("analytics: forbidden property key")
	ErrInvalidPropertyValue = errors.New("analytics: property value must be a finite JSON scalar")
	ErrTooManyProperties    = errors.New("analytics: too many properties")
	ErrPropertyTooLarge     = errors.New("analytics: property value exceeds size cap")
	ErrEventTooLarge        = errors.New("analytics: event exceeds size cap")
	ErrInvalidContext       = errors.New("analytics: invalid event context field")
	ErrUnknownEvent         = errors.New("analytics: unknown event name")
	ErrMissingProperty      = errors.New("analytics: missing required property")
	ErrPropertyTypeMismatch = errors.New("analytics: property type mismatch")
	ErrProfileNotFound      = errors.New("analytics: account profile not found")
	ErrInvalidAccount       = errors.New("analytics: invalid account")
)

Sentinel errors returned by event, property and catalog validation.

Functions

func Days

func Days(dir string) ([]string, error)

Days returns the sorted list of UTC calendar day names ("yyyy-mm-dd") present in dir.

func EncodeCatalog

func EncodeCatalog(c *Catalog) ([]byte, error)

EncodeCatalog writes deterministic YAML for c after validating it.

func EncodeConfig

func EncodeConfig(c Config) ([]byte, error)

EncodeConfig writes deterministic YAML for c after validating it.

func EncodeRecord

func EncodeRecord(r Record) ([]byte, error)

EncodeRecord encodes r as one deterministic JSON line (without trailing newline).

func ForbiddenKeys

func ForbiddenKeys() []string

ForbiddenKeys returns a sorted copy of the documented list of property keys that must never be sent in analytics events or account property updates (emails, phone numbers, credentials, IP addresses, legal names and free text).

func IsForbiddenKey

func IsForbiddenKey(key string) bool

IsForbiddenKey reports whether key matches one of the forbidden PII or free-text keys. Comparison is ASCII case-insensitive and normalizes '-' and '.' separators to '_'.

func NewHTTPSink

func NewHTTPSink(opts HTTPSinkOptions) (func([]byte) error, error)

NewHTTPSink returns a batch upload function that gzip-compresses JSON Lines payloads and POSTs them to opts.Endpoint. It matches liveops.BatchSink.

func PostBatch

func PostBatch(ctx context.Context, client *http.Client, endpoint string, token func() string, batch []byte) error

PostBatch gzip-compresses a JSON Lines batch and POSTs it to endpoint.

func ValidateEvent

func ValidateEvent(ev Event, limits Limits) error

ValidateEvent checks an event's name, context field lengths, properties and approximate encoded byte budget without allocating on the valid fast path.

func ValidateEventName

func ValidateEventName(name string, maxLen int) error

ValidateEventName checks that name is a non-empty identifier within maxLen bytes starting with an ASCII letter and containing only ASCII letters, digits, '_', '.' or '-'.

func ValidateProperties

func ValidateProperties(props map[string]any, limits Limits) error

ValidateProperties validates a property map against limits without allocating on the valid fast path.

func ValidatePropertyKey

func ValidatePropertyKey(key string, maxLen int) error

ValidatePropertyKey checks that key is a valid identifier within maxLen bytes and is not in ForbiddenKeys.

func ValidatePropertyValue

func ValidatePropertyValue(v any, maxStringLen int) error

ValidatePropertyValue checks that v is a finite JSON scalar (nil, bool, integer, finite float, finite json.Number or string within maxStringLen). Objects, slices, structs and non-finite floats are refused.

Types

type AccountProfile

type AccountProfile struct {
	// Account is the player's account ID.
	Account string `json:"account"`
	// FirstSeen is the earliest UTC timestamp observed for this account.
	FirstSeen time.Time `json:"first_seen"`
	// LastSeen is the most recent UTC timestamp observed for this account.
	LastSeen time.Time `json:"last_seen"`
	// Properties holds merged per-account custom scalar attributes.
	Properties map[string]any `json:"properties,omitempty"`
}

AccountProfile stores per-account first-seen and last-seen timestamps alongside custom scalar properties for audience targeting.

type Catalog

type Catalog struct {
	// Version must equal CatalogVersion (1).
	Version int `yaml:"version"`
	// UnknownEvents controls whether unlisted event names are accepted ("accept", default) or refused ("refuse").
	UnknownEvents UnknownEventPolicy `yaml:"unknownEvents,omitempty"`
	// MaxProperties caps properties per event (0 uses DefaultMaxProperties).
	MaxProperties int `yaml:"maxProperties,omitempty"`
	// MaxPropertyLength caps string property byte length (0 uses DefaultMaxPropertyStringLength).
	MaxPropertyLength int `yaml:"maxPropertyLength,omitempty"`
	// MaxEventBytes caps encoded event size in bytes (0 uses DefaultMaxEventBytes).
	MaxEventBytes int `yaml:"maxEventBytes,omitempty"`
	// Events lists known events in declaration order.
	Events []EventSpec `yaml:"events,omitempty"`
	// contains filtered or unexported fields
}

Catalog is a versioned YAML schema declaring valid analytics events and size caps.

func ParseCatalog

func ParseCatalog(data []byte) (*Catalog, error)

ParseCatalog parses and validates a strict versioned analytics catalog YAML document. Unknown fields, trailing YAML documents, unsupported versions, duplicate names and forbidden property keys are refused with a *loaderr.Error.

func (*Catalog) Limits

func (c *Catalog) Limits() Limits

Limits returns the global event Limits derived from the catalog.

func (*Catalog) Validate

func (c *Catalog) Validate() error

Validate checks the catalog's version, policy, limits and event/property declarations.

func (*Catalog) ValidateEvent

func (c *Catalog) ValidateEvent(ev Event) error

ValidateEvent validates ev against the catalog's global caps, unknown-event policy and per-event property specifications.

type Config

type Config struct {
	// Version must equal ConfigVersion (1).
	Version int `yaml:"version"`
	// Audience is the account token audience accepted on Authorization: Bearer headers (defaults to DefaultAudience).
	Audience string `yaml:"audience,omitempty"`
	// RequireAuth refuses unauthenticated POST /v1/events requests when true; false allows anonymous consented events while verifying any token that is sent.
	RequireAuth bool `yaml:"requireAuth,omitempty"`
	// AllowedOrigins lists browser origins permitted by CORS preflight responses.
	AllowedOrigins []string `yaml:"allowedOrigins,omitempty"`
	// RetainDays is how many days of daily JSON Lines files FileSink keeps (0 keeps all).
	RetainDays int `yaml:"retainDays,omitempty"`
	// MaxBatchBytes caps uncompressed POST /v1/events payload size in bytes (0 uses DefaultMaxBatchBytes).
	MaxBatchBytes int `yaml:"maxBatchBytes,omitempty"`
	// MaxBatchEvents caps events per POST /v1/events request (0 uses DefaultMaxBatchEvents).
	MaxBatchEvents int `yaml:"maxBatchEvents,omitempty"`
	// Metrics optionally binds a dedicated listener serving /healthz, /readyz and /metrics.
	Metrics string `yaml:"metrics,omitempty"`
}

Config is the versioned YAML configuration of a self-hosted analytics collector (cmd/analyticsd).

func ParseConfig

func ParseConfig(data []byte) (Config, error)

ParseConfig parses and validates a strict versioned analytics collector YAML configuration.

func (Config) TokenAudience

func (c Config) TokenAudience() string

TokenAudience returns Config.Audience or DefaultAudience when unset.

func (Config) Validate

func (c Config) Validate() error

Validate checks Config fields for valid ranges and syntax.

type Event

type Event struct {
	// Name identifies the event kind (for example "level_complete").
	Name string `json:"name"`
	// Properties holds optional JSON-scalar attributes for the event.
	Properties map[string]any `json:"properties,omitempty"`
	// Time is when the event occurred.
	Time time.Time `json:"time"`
	// Install is a random per-install identifier rotated when consent is revoked.
	Install string `json:"install,omitempty"`
	// Session identifies the active play session, rotated after SessionTimeout in the background.
	Session string `json:"session,omitempty"`
	// Seq is a monotonically increasing sequence number per Install used with Install for idempotent deduplication.
	Seq uint64 `json:"seq,omitempty"`
	// AppVersion is the semantic or build version of the game client.
	AppVersion string `json:"app_version,omitempty"`
	// Platform identifies the client operating system or runtime (for example "ios", "android", "web").
	Platform string `json:"platform,omitempty"`
	// Locale is the player's BCP-47 locale tag (for example "en-US", "zh-CN").
	Locale string `json:"locale,omitempty"`
}

Event is one analytics event emitted by a game client or server.

func DecodeEvent

func DecodeEvent(data []byte) (Event, error)

DecodeEvent strictly decodes one client Event JSON line.

type EventSpec

type EventSpec struct {
	// Name is the unique event name.
	Name string `yaml:"name"`
	// Description documents the event's meaning for analysts and reviewers.
	Description string `yaml:"description,omitempty"`
	// MaxProperties overrides the maximum number of properties for this event (0 uses the catalog default).
	MaxProperties int `yaml:"maxProperties,omitempty"`
	// MaxBytes overrides the maximum encoded size for this event (0 uses the catalog default).
	MaxBytes int `yaml:"maxBytes,omitempty"`
	// Properties declares typed or required properties for this event.
	Properties []PropertySpec `yaml:"properties,omitempty"`
}

EventSpec declares validation rules for one named analytics event.

type FileSink

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

FileSink writes deduplicated analytics records into daily UTC JSON Lines files (<yyyy-mm-dd>.jsonl) for downstream warehouse ingestion, and keeps per-account properties and first/last-seen timestamps in profiles.json.

func OpenFileSink

func OpenFileSink(opts FileSinkOptions) (*FileSink, error)

OpenFileSink opens or creates a FileSink in opts.Dir, loading existing daily deduplication keys and profiles.json so restarts remain idempotent.

func (*FileSink) Close

func (f *FileSink) Close() error

Close marks the FileSink closed. It is safe to call more than once.

func (*FileSink) Profile

func (f *FileSink) Profile(ctx context.Context, account string) (AccountProfile, error)

Profile returns account's stored AccountProfile, or ErrProfileNotFound.

func (*FileSink) UpdateProfile

func (f *FileSink) UpdateProfile(ctx context.Context, account string, seenAt time.Time, props map[string]any) (AccountProfile, error)

UpdateProfile upserts account's first-seen, last-seen and merged scalar properties and writes profiles.json atomically.

func (*FileSink) WriteEvents

func (f *FileSink) WriteEvents(ctx context.Context, records []Record) (int, error)

WriteEvents appends deduplicated records to the UTC day file matching each record's Time.

type FileSinkOptions

type FileSinkOptions struct {
	// Dir is the directory holding daily <yyyy-mm-dd>.jsonl event files and profiles.json. Required.
	Dir string
	// Retain is how many UTC days of daily .jsonl files to keep; 0 keeps every file.
	Retain int
	// Sync fsyncs daily files after each batch write when true.
	Sync bool
}

FileSinkOptions configures FileSink.

type HTTPError

type HTTPError struct {
	StatusCode int
	Body       string
}

HTTPError is returned by the HTTP sink when the collector answers with a non-2xx status.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error formats the HTTP status code and optional response body returned by the collector.

type HTTPSinkOptions

type HTTPSinkOptions struct {
	// Endpoint is the collector's POST /v1/events URL. Required.
	Endpoint string
	// Client is the HTTP client used to upload batches (defaults to a 15s timeout client).
	Client *http.Client
	// Token optionally returns a player bearer token attached as Authorization: Bearer <token>.
	// Returning an empty string sends the batch anonymously.
	Token func() string
}

HTTPSinkOptions configures the built-in gzipped JSON Lines HTTP client sink.

type IngestResult

type IngestResult struct {
	Accepted   int `json:"accepted"`
	Duplicates int `json:"duplicates"`
}

IngestResult reports how many events in a batch were persisted vs dropped as duplicates.

type Limits

type Limits struct {
	MaxEventNameLength      int
	MaxProperties           int
	MaxPropertyKeyLength    int
	MaxPropertyStringLength int
	MaxEventBytes           int
}

Limits configures validation size caps for events and properties. Zero fields fall back to DefaultLimits().

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the default validation caps.

type MemorySink

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

MemorySink is an in-memory Sink suitable for tests and ephemeral collectors.

func NewMemorySink

func NewMemorySink() *MemorySink

NewMemorySink returns an empty MemorySink.

func (*MemorySink) Profile

func (m *MemorySink) Profile(ctx context.Context, account string) (AccountProfile, error)

Profile returns the stored AccountProfile for account, or ErrProfileNotFound.

func (*MemorySink) Records

func (m *MemorySink) Records() []Record

Records returns a defensive copy of all persisted records in ingestion order.

func (*MemorySink) UpdateProfile

func (m *MemorySink) UpdateProfile(ctx context.Context, account string, seenAt time.Time, props map[string]any) (AccountProfile, error)

UpdateProfile upserts account's first-seen, last-seen and merged scalar properties.

func (*MemorySink) WriteEvents

func (m *MemorySink) WriteEvents(ctx context.Context, records []Record) (int, error)

WriteEvents appends non-duplicate records into memory.

type PropertySpec

type PropertySpec struct {
	// Name is the property key (unique within its EventSpec, never a forbidden PII key).
	Name string `yaml:"name"`
	// Type restricts the scalar type: any, string, number or bool (defaults to any).
	Type PropertyType `yaml:"type,omitempty"`
	// Required requires the property to be present and non-nil on every matching event.
	Required bool `yaml:"required,omitempty"`
	// MaxLength caps string byte length for this property (0 uses the catalog default).
	MaxLength int `yaml:"maxLength,omitempty"`
}

PropertySpec declares validation rules for one event property.

type PropertyType

type PropertyType string

PropertyType restricts the JSON scalar kind accepted for a cataloged property.

const (
	// PropertyAny accepts any finite JSON scalar (default when omitted).
	PropertyAny PropertyType = "any"
	// PropertyString accepts only string values.
	PropertyString PropertyType = "string"
	// PropertyNumber accepts only finite numeric values.
	PropertyNumber PropertyType = "number"
	// PropertyBool accepts only boolean values.
	PropertyBool PropertyType = "bool"
)

type Record

type Record struct {
	// V is the record schema version (RecordVersion).
	V int `json:"v"`
	// ReceivedAt is when the collector accepted the event.
	ReceivedAt time.Time `json:"received_at"`
	// Account is the verified account ID when authenticated, or empty for anonymous events.
	Account string `json:"account,omitempty"`
	// Source is SourceClient or SourceServer.
	Source string `json:"source,omitempty"`
	Event
}

Record is one validated analytics event persisted by a Sink.

func DecodeRecord

func DecodeRecord(data []byte) (Record, error)

DecodeRecord strictly decodes one JSON line written by EncodeRecord.

func DeriveSessionEvents

func DeriveSessionEvents(records []Record) []Record

DeriveSessionEvents derives EventSessionStart ("session_start") and EventSessionEnd ("session_end") records from records' Session IDs. Each session produces a session_start record at Session.Start and a session_end record at Session.End carrying duration_ms and event_count.

func ReadDay

func ReadDay(dir, day string) ([]Record, error)

ReadDay reads and strictly decodes every JSON Lines record from <dir>/<day>.jsonl.

type Service

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

Service validates, deduplicates and persists client batches, server-side events and per-account custom properties through a Sink.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/online/liveops/analytics"
)

func main() {
	now := time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC)
	cat, err := analytics.ParseCatalog([]byte("version: 1\nunknownEvents: refuse\nevents:\n  - name: match_result\n    properties:\n      - name: won\n        type: bool\n        required: true\n"))
	if err != nil {
		fmt.Println(err)
		return
	}
	sink := analytics.NewMemorySink()
	svc, err := analytics.NewService(analytics.ServiceOptions{
		Sink:    sink,
		Catalog: cat,
		Now:     func() time.Time { return now },
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	ctx := context.Background()
	if err := svc.Emit(ctx, "acct-1", analytics.Event{
		Name:       "match_result",
		Properties: map[string]any{"won": true},
	}); err != nil {
		fmt.Println(err)
		return
	}
	prof, err := svc.UpdateProperties(ctx, "acct-1", map[string]any{"tier": "gold"})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(len(sink.Records()), prof.Account, prof.Properties["tier"])
}
Output:
1 acct-1 gold

func NewService

func NewService(opts ServiceOptions) (*Service, error)

NewService constructs a collector Service backed by opts.Sink.

func (*Service) Emit

func (s *Service) Emit(ctx context.Context, account string, ev Event) error

Emit validates and records a single server-side event (such as a match result or granted purchase) through the same catalog and sink as client batches.

func (*Service) Handler

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

Handler serves the analytics HTTP sink contract:

POST /v1/events      gzip or plain JSON Lines batch -> {"accepted": N, "duplicates": M}
POST /v1/properties  authenticated JSON {"properties": {...}} -> AccountProfile

POST /v1/events verifies an optional Authorization: Bearer <token> header with ServiceOptions.Tokens (or requires one when ServiceOptions.RequireAuth is true). An invalid or expired token always returns 401 invalid_token. POST /v1/properties always requires a valid account bearer token.

The handler can be served directly by cmd/analyticsd or mounted into pkg/online/backend via backend.Mount("/analytics", svc.Handler()).

func (*Service) Ingest

func (s *Service) Ingest(ctx context.Context, account string, events []Event) (IngestResult, error)

Ingest validates a batch of client events, writes non-duplicate records to the sink and updates the authenticated account's first-seen/last-seen window.

func (*Service) Profile

func (s *Service) Profile(ctx context.Context, account string) (AccountProfile, error)

Profile returns the stored AccountProfile for account, or ErrProfileNotFound.

func (*Service) UpdateProperties

func (s *Service) UpdateProperties(ctx context.Context, account string, props map[string]any) (AccountProfile, error)

UpdateProperties validates and merges per-account custom scalar properties while updating the account's first-seen and last-seen timestamps.

type ServiceOptions

type ServiceOptions struct {
	// Sink persists validated events and per-account profiles. Required.
	Sink Sink
	// Catalog validates incoming event names, property types and size caps.
	// When nil, unknown events are accepted under DefaultLimits().
	Catalog *Catalog
	// Tokens verifies optional or required Authorization: Bearer account tokens.
	Tokens TokenVerifier
	// RequireAuth refuses unauthenticated POST /v1/events requests when true.
	// When false, unauthenticated events are accepted anonymously while any
	// Authorization header that is present is still strictly verified.
	RequireAuth bool
	// MaxBatchBytes caps the uncompressed POST /v1/events body (DefaultMaxBatchBytes when <= 0).
	MaxBatchBytes int
	// MaxBatchEvents caps events in one POST /v1/events batch (DefaultMaxBatchEvents when <= 0).
	MaxBatchEvents int
	// AllowedOrigins sets browser CORS origins permitted by Handler().
	AllowedOrigins []string
	// Now overrides the collector clock for tests (defaults to time.Now).
	Now func() time.Time
}

ServiceOptions configures an analytics collector Service.

type Session

type Session struct {
	Install    string
	Session    string
	Account    string
	Start      time.Time
	End        time.Time
	Duration   time.Duration
	EventCount int
	AppVersion string
	Platform   string
	Locale     string
}

Session summarizes one play session derived solely from the Session IDs of ingested events, avoiding fragile client-emitted session_end hooks.

func DeriveSessions

func DeriveSessions(records []Record) []Session

DeriveSessions groups records by (Install, Session) and computes each session's start time, end time, duration and event count in deterministic order (by Start, then Install, then Session). Records without a Session ID are ignored.

type Sink

type Sink interface {
	// WriteEvents stores records, dropping duplicates whose (Install, Seq) pair
	// (when Install != "" and Seq > 0) has already been persisted. It returns the
	// count of newly accepted records.
	WriteEvents(ctx context.Context, records []Record) (accepted int, err error)
	// UpdateProfile merges props into account's custom properties and updates
	// FirstSeen (earliest observed time) and LastSeen (latest observed time).
	UpdateProfile(ctx context.Context, account string, seenAt time.Time, props map[string]any) (AccountProfile, error)
	// Profile returns the stored AccountProfile for account, or ErrProfileNotFound.
	Profile(ctx context.Context, account string) (AccountProfile, error)
}

Sink persists validated analytics records and per-account custom properties. Implementations must be safe for concurrent use.

type TokenVerifier

type TokenVerifier interface {
	Verify(token string) (authtoken.Claims, error)
}

TokenVerifier verifies a bearer account token. *authtoken.Verifier implements it.

type UnknownEventPolicy

type UnknownEventPolicy string

UnknownEventPolicy controls how the collector handles events not listed in the catalog.

const (
	// UnknownEventsAccept validates unknown events against the global limits and accepts them (default).
	UnknownEventsAccept UnknownEventPolicy = "accept"
	// UnknownEventsRefuse rejects any event whose name is not declared in Catalog.Events.
	UnknownEventsRefuse UnknownEventPolicy = "refuse"
)

Directories

Path Synopsis
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Jump to

Keyboard shortcuts

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