Documentation
¶
Overview ¶
Package analytics provides the dynamic, per-site analytics engine for Kora. It uses a rollup-based approach: document writes emit events, a worker pre-computes aggregates into _kora_analytics_* tables in the operational DB.
Index ¶
- func BootstrapTables(database *sql.DB, dialect db.SchemaDialect) error
- func MigrateRollupMetrics(db *sql.DB, siteName string, oldDoctypes, newDoctypes []*doctype.DocType) error
- func NewLocalProvider(bus EventBus) contract.EventPublisher
- func SendCloudProductEvent(client *http.Client, cfg CloudRelayConfig, event CloudProductEventDTO, ...)
- type ChangeEvent
- type CloudProductEventDTO
- type CloudRelay
- type CloudRelayConfig
- type Config
- type DataPointKind
- type DataPointSpec
- type EventBus
- type EventOp
- type FirstDocTypePropertiesDTO
- type FirstLoginPropertiesDTO
- type FirstRecordPropertiesDTO
- type LocalProvider
- type Metric
- type MetricFilter
- type MetricType
- type MultiBus
- type QueryEngine
- func (qe *QueryEngine) CachedResolve(metric *Metric, req QueryRequest, ttl time.Duration) (*QueryResult, error)
- func (qe *QueryEngine) InvalidateCache()
- func (qe *QueryEngine) Resolve(metric *Metric, req QueryRequest) (*QueryResult, error)
- func (qe *QueryEngine) ResolveInsights(doctype string, metrics []*Metric) (map[string]any, error)
- type QueryRequest
- type QueryResult
- type Status
- type Worker
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BootstrapTables ¶
func BootstrapTables(database *sql.DB, dialect db.SchemaDialect) error
BootstrapTables creates the analytics rollup tables in the operational DB. Idempotent — uses IF NOT EXISTS. Called once per site at startup.
func MigrateRollupMetrics ¶
func MigrateRollupMetrics(db *sql.DB, siteName string, oldDoctypes, newDoctypes []*doctype.DocType) error
MigrateRollupMetrics consumes a ConfigDiff and updates _kora_analytics_daily and _kora_analytics_monthly to reflect field renames and doctype changes. Call after config activation/rollback.
func NewLocalProvider ¶
func NewLocalProvider(bus EventBus) contract.EventPublisher
NewLocalProvider wraps an EventBus as a contract.EventPublisher.
func SendCloudProductEvent ¶
func SendCloudProductEvent(client *http.Client, cfg CloudRelayConfig, event CloudProductEventDTO, dedupeKey string)
Types ¶
type ChangeEvent ¶
type ChangeEvent struct {
Site string `json:"site"`
Doctype string `json:"doctype"`
DocName string `json:"doc_name"`
Operation EventOp `json:"operation"`
Timestamp time.Time `json:"timestamp"`
ModifiedBy string `json:"modified_by"`
Data map[string]any `json:"data"` // full document fields after write
OldData map[string]any `json:"old_data,omitempty"` // previous state (update/delete only)
}
ChangeEvent captures a document write for analytics ingestion. Emitted by the ORM after every write — async, non-blocking.
type CloudProductEventDTO ¶
type CloudRelay ¶
type CloudRelay struct {
Bus *MultiBus
Site string
Config CloudRelayConfig
// contains filtered or unexported fields
}
func NewCloudRelay ¶
func NewCloudRelay(bus *MultiBus, site string, cfg CloudRelayConfig) *CloudRelay
func (*CloudRelay) Start ¶
func (r *CloudRelay) Start()
func (*CloudRelay) Stop ¶
func (r *CloudRelay) Stop()
type CloudRelayConfig ¶
func LoadCloudRelayConfig ¶
func LoadCloudRelayConfig() *CloudRelayConfig
type Config ¶
type Config struct {
ChannelSize int // event bus buffer capacity (default 1000)
BatchSize int // flush worker deltas after N events (default 100)
FlushInterval string // flush worker deltas after duration (default "1s")
RetentionDays int // how long to keep daily rollup rows (default 30; 0 = indefinite)
WALDir string // write-ahead log for spilled events (default "data/analytics/wal")
}
Config holds analytics engine configuration. All values have sensible defaults.
func LoadConfig ¶
func LoadConfig() *Config
LoadConfig reads analytics configuration from environment variables.
type DataPointKind ¶
type DataPointKind string
DataPointKind is the generic analytical shape derived from a DocType. It is the stable model behind auto-generated metrics and page insights.
const ( DataPointCount DataPointKind = "count" DataPointCreatedDaily DataPointKind = "created_daily" DataPointCountByField DataPointKind = "count_by_field" DataPointSum DataPointKind = "sum" DataPointStateDistribution DataPointKind = "state_distribution" DataPointWorkflowDuration DataPointKind = "workflow_duration" )
type DataPointSpec ¶
type DataPointSpec struct {
Name string `json:"name" yaml:"name"`
Label string `json:"label" yaml:"label"`
Kind DataPointKind `json:"kind" yaml:"kind"`
DocType string `json:"doctype" yaml:"doctype"`
Field string `json:"field,omitempty" yaml:"field,omitempty"`
LinkField string `json:"link_field,omitempty" yaml:"link_field,omitempty"`
TimeField string `json:"time_field,omitempty" yaml:"time_field,omitempty"`
FromState string `json:"from_state,omitempty" yaml:"from_state,omitempty"`
ToState string `json:"to_state,omitempty" yaml:"to_state,omitempty"`
Auto bool `json:"auto" yaml:"auto"`
}
DataPointSpec describes one analytic fact family that can be tracked for a DocType. A single DocType can yield many point specs from its fields and workflow definition.
func BuildDataPointCatalog ¶
func BuildDataPointCatalog(dt *doctype.DocType, wf *doctype.Workflow) []DataPointSpec
BuildDataPointCatalog returns the generic data points implied by a DocType and its workflow. This is the shape we can expose in page manifests.
type EventBus ¶
type EventBus interface {
// Publish sends an event. Never blocks — writes to WAL first, then
// best-effort channel send. Returns nil even on WAL failure (logs + counts).
Publish(event ChangeEvent) error
// Subscribe returns a channel that receives events. Only one subscriber per bus.
Subscribe() (<-chan ChangeEvent, error)
// DrainWAL replays any events in the WAL through the given handler.
// Called once at startup before consuming live events to recover from crashes.
DrainWAL(handler func(ChangeEvent)) (int, error)
// RotateWAL atomically swaps the current WAL file with a fresh one.
// Returns the path of the old WAL file. After a successful DB flush, the
// caller should call CommitWALRotation() to delete the old file.
// If CommitWALRotation is not called (crash), the old WAL is replayed on
// next restart alongside the current WAL.
RotateWAL() (oldWALPath string, err error)
// CommitWALRotation deletes a rotated WAL file after its events have been
// flushed to the database. This confirms the data is safely in the DB.
CommitWALRotation(oldWALPath string) error
// Dropped returns the count of events lost due to WAL write failures.
Dropped() int64
// Close shuts down the event bus and flushes any pending WAL.
Close() error
}
EventBus is the interface for publishing and subscribing to change events. The default implementation is an in-process buffered channel with WAL-first durability: every event is written to disk before entering the channel.
func NewChannelBus ¶
NewChannelBus creates an in-process event bus with WAL-first durability. capacity is the channel buffer size (default 1000 if <= 0). walDir is where the write-ahead log is stored.
type FirstLoginPropertiesDTO ¶
type LocalProvider ¶
type LocalProvider struct {
// contains filtered or unexported fields
}
LocalProvider adapts the in-process/WAL EventBus to the provider-neutral contract.EventPublisher interface (RFC §7). The WAL rotation/replay machinery remains behind this provider and is not part of the public EventPublisher contract.
func (*LocalProvider) Publish ¶
func (p *LocalProvider) Publish(ctx context.Context, event contract.EventEnvelope) error
Publish converts an EventEnvelope into a ChangeEvent and publishes it through the underlying in-process bus. Conversion is best-effort: fields that do not map cleanly (e.g., aggregate identity) are carried through the Data payload.
type Metric ¶
type Metric struct {
Name string `json:"name" yaml:"name"`
Label string `json:"label" yaml:"label"`
Type MetricType `json:"type" yaml:"type"`
DocType string `json:"doctype" yaml:"doctype"`
Field string `json:"field,omitempty" yaml:"field,omitempty"` // for count_by_field, sum, avg
LinkField string `json:"link_field,omitempty" yaml:"link_field,omitempty"` // for count_by_linked_field
GroupByField string `json:"group_by_field,omitempty" yaml:"group_by_field,omitempty"` // for count_by_linked_field
TimeField string `json:"time_field,omitempty" yaml:"time_field,omitempty"` // for count_by_time
Filters []MetricFilter `json:"filters,omitempty" yaml:"filters,omitempty"`
AutoGenerated bool `json:"auto_generated" yaml:"auto_generated"` // true if generated from DocType metadata
}
Metric defines a single analytics metric — either auto-generated from DocType metadata or user-defined via YAML / admin UI.
func GenerateMetrics ¶
GenerateMetrics produces baseline metrics for a DocType from its field metadata. These are the "Level 0" metrics that appear on the Insights tab with zero config.
type MetricFilter ¶
type MetricFilter struct {
Field string `json:"field" yaml:"field"`
Operator string `json:"op" yaml:"op"`
Value string `json:"value" yaml:"value"`
}
MetricFilter is a simple field=value filter on a metric.
type MetricType ¶
type MetricType string
MetricType enumerates how a metric is computed.
const ( MetricCount MetricType = "count" MetricCountByField MetricType = "count_by_field" MetricCountByTime MetricType = "count_by_time" MetricSum MetricType = "sum" MetricAvg MetricType = "avg" MetricStateDistribution MetricType = "state_distribution" MetricCountByLinkedField MetricType = "count_by_linked_field" )
type MultiBus ¶
type MultiBus struct {
// contains filtered or unexported fields
}
MultiBus wraps an EventBus and fans out events to multiple subscribers. The primary subscriber continues using EventBus.Subscribe(). Additional subscribers use MultiBus.AddListener().
func NewMultiBus ¶
NewMultiBus creates a fan-out wrapper around an existing EventBus. It starts a goroutine that reads from the inner bus and fans out to all listeners.
func (*MultiBus) AddListener ¶
func (mb *MultiBus) AddListener(ch chan ChangeEvent)
AddListener registers a new subscriber channel. Events are fanned out to all listeners. The channel should be buffered to avoid blocking the fan-out goroutine.
func (*MultiBus) ListenerCount ¶
ListenerCount returns the number of listeners.
func (*MultiBus) RemoveListener ¶
func (mb *MultiBus) RemoveListener(ch chan ChangeEvent)
RemoveListener removes a subscriber channel.
type QueryEngine ¶
QueryEngine resolves metric queries against the rollup tables.
func (*QueryEngine) CachedResolve ¶
func (qe *QueryEngine) CachedResolve(metric *Metric, req QueryRequest, ttl time.Duration) (*QueryResult, error)
CachedResolve returns a cached result if available and not expired. Otherwise, delegates to Resolve and caches the result for the given TTL.
func (*QueryEngine) InvalidateCache ¶
func (qe *QueryEngine) InvalidateCache()
InvalidateCache clears all cached results for this engine.
func (*QueryEngine) Resolve ¶
func (qe *QueryEngine) Resolve(metric *Metric, req QueryRequest) (*QueryResult, error)
Resolve executes a pre-computed metric query against the rollup tables. Metrics are stored as rows in _kora_analytics_daily (or _monthly for month+ ranges). The query is a simple read of pre-aggregated values — no scanning of business tables.
func (*QueryEngine) ResolveInsights ¶
ResolveInsights returns pre-computed numbers for a doctype — designed for AI consumption. Returns a flat map of metric_name → current value, plus trend indicators.
type QueryRequest ¶
type QueryRequest struct {
Metric string `json:"metric"`
From string `json:"from,omitempty"` // ISO date, inclusive
To string `json:"to,omitempty"` // ISO date, inclusive
GroupBy string `json:"group_by,omitempty"` // "day" | "week" | "month"
Limit int `json:"limit,omitempty"`
}
QueryRequest holds parameters for a metric query.
type QueryResult ¶
type QueryResult struct {
Metric string `json:"metric"`
Columns []string `json:"columns"`
Rows []map[string]any `json:"rows"`
Total int `json:"total"`
}
QueryResult holds the result of a metric query.
type Status ¶
type Status struct {
Enabled bool `json:"enabled"`
EventsProcessed int64 `json:"events_processed"`
EventsDropped int64 `json:"events_dropped"`
}
Status holds the analytics pipeline status for a site.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker consumes ChangeEvents from the EventBus and pre-computes rollups into _kora_analytics_daily and _kora_analytics_workflow tables.
Design: batch-and-merge. Instead of UPSERTing on every event, the worker accumulates deltas in memory and flushes periodically. Multiple increments to the same (metric, dimension, date) row are merged into a single UPSERT.
Workflow transitions are also batched: the UPDATE (close previous) and INSERT (new transition) are accumulated in memory and flushed in the same transaction as the daily rollup deltas, eliminating 2 extra DB round-trips per transition.
func NewWorker ¶
func NewWorker(bus EventBus, database *sql.DB, dialect db.QueryDialect, registry *doctype.Registry, siteName string, cfg *Config) *Worker
NewWorker creates an analytics worker for a single site.
func (*Worker) Flush ¶
func (w *Worker) Flush()
Flush forces any buffered analytics deltas to persist immediately. It is safe to call even if no events are pending.
func (*Worker) InvalidateAllMetrics ¶
func (w *Worker) InvalidateAllMetrics()
InvalidateAllMetrics clears all cached metrics for all doctypes. Call after a full config reload or site rebuild.
func (*Worker) InvalidateMetrics ¶
InvalidateMetrics clears cached metrics for a single doctype, forcing re-generation on the next event. Call after config activation/rollback/reload.