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 ¶
- Constants
- Variables
- func Days(dir string) ([]string, error)
- func EncodeCatalog(c *Catalog) ([]byte, error)
- func EncodeConfig(c Config) ([]byte, error)
- func EncodeRecord(r Record) ([]byte, error)
- func ForbiddenKeys() []string
- func IsForbiddenKey(key string) bool
- func NewHTTPSink(opts HTTPSinkOptions) (func([]byte) error, error)
- func PostBatch(ctx context.Context, client *http.Client, endpoint string, token func() string, ...) error
- func ValidateEvent(ev Event, limits Limits) error
- func ValidateEventName(name string, maxLen int) error
- func ValidateProperties(props map[string]any, limits Limits) error
- func ValidatePropertyKey(key string, maxLen int) error
- func ValidatePropertyValue(v any, maxStringLen int) error
- type AccountProfile
- type Catalog
- type Config
- type Event
- type EventSpec
- type FileSink
- func (f *FileSink) Close() error
- func (f *FileSink) Profile(ctx context.Context, account string) (AccountProfile, error)
- func (f *FileSink) UpdateProfile(ctx context.Context, account string, seenAt time.Time, props map[string]any) (AccountProfile, error)
- func (f *FileSink) WriteEvents(ctx context.Context, records []Record) (int, error)
- type FileSinkOptions
- type HTTPError
- type HTTPSinkOptions
- type IngestResult
- type Limits
- type MemorySink
- func (m *MemorySink) Profile(ctx context.Context, account string) (AccountProfile, error)
- func (m *MemorySink) Records() []Record
- func (m *MemorySink) UpdateProfile(ctx context.Context, account string, seenAt time.Time, props map[string]any) (AccountProfile, error)
- func (m *MemorySink) WriteEvents(ctx context.Context, records []Record) (int, error)
- type PropertySpec
- type PropertyType
- type Record
- type Service
- func (s *Service) Emit(ctx context.Context, account string, ev Event) error
- func (s *Service) Handler() http.Handler
- func (s *Service) Ingest(ctx context.Context, account string, events []Event) (IngestResult, error)
- func (s *Service) Profile(ctx context.Context, account string) (AccountProfile, error)
- func (s *Service) UpdateProperties(ctx context.Context, account string, props map[string]any) (AccountProfile, error)
- type ServiceOptions
- type Session
- type Sink
- type TokenVerifier
- type UnknownEventPolicy
Examples ¶
Constants ¶
const ( SourceClient = "client" SourceServer = "server" )
Source values identify whether an event arrived from a game client or server code.
const ( EventSessionStart = "session_start" EventSessionEnd = "session_end" )
Derived session lifecycle event names produced from session IDs.
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.
const CatalogVersion = 1
CatalogVersion is the schema version of an analytics event catalog YAML file.
const ConfigVersion = 1
ConfigVersion is the schema version of an analytics collector config YAML file.
const DefaultAudience = "analytics"
DefaultAudience is the JWT audience the collector accepts when Config.Audience is empty.
const ProfilesVersion = 1
ProfilesVersion is the schema version of FileSink's profiles.json file.
const RecordVersion = 1
RecordVersion is the schema version written as "v" on each collector JSON Lines record.
Variables ¶
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 EncodeCatalog ¶
EncodeCatalog writes deterministic YAML for c after validating it.
func EncodeConfig ¶
EncodeConfig writes deterministic YAML for c after validating it.
func EncodeRecord ¶
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 ¶
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 ¶
ValidateEvent checks an event's name, context field lengths, properties and approximate encoded byte budget without allocating on the valid fast path.
func ValidateEventName ¶
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 ¶
ValidateProperties validates a property map against limits without allocating on the valid fast path.
func ValidatePropertyKey ¶
ValidatePropertyKey checks that key is a valid identifier within maxLen bytes and is not in ForbiddenKeys.
func ValidatePropertyValue ¶
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 ¶
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) Validate ¶
Validate checks the catalog's version, policy, limits and event/property declarations.
func (*Catalog) ValidateEvent ¶
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 ¶
ParseConfig parses and validates a strict versioned analytics collector YAML configuration.
func (Config) TokenAudience ¶
TokenAudience returns Config.Audience or DefaultAudience when unset.
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 ¶
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.
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 ¶
HTTPError is returned by the HTTP sink when the collector answers with a non-2xx status.
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 ¶
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().
type MemorySink ¶
type MemorySink struct {
// contains filtered or unexported fields
}
MemorySink is an in-memory Sink suitable for tests and ephemeral collectors.
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 ¶
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 ¶
DecodeRecord strictly decodes one JSON line written by EncodeRecord.
func DeriveSessionEvents ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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" )
Source Files
¶
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/. |