analytics

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 28 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

Index

Constants

View Source
const (
	DefaultMaxEventBytes     = 1 << 20
	DefaultMaxQueuedBytes    = 64 << 20
	MaxConfiguredQueuedBytes = 1 << 30
	MaxChannelCapacity       = 10_000
)
View Source
const (
	DefaultAnalyticsBatchSize = 100
	MaxAnalyticsBatchSize     = 500
)
View Source
const (
	EventInsert       = eventstream.EventInsert
	EventUpdate       = eventstream.EventUpdate
	EventDelete       = eventstream.EventDelete
	EventSubmit       = eventstream.EventSubmit
	EventCancel       = eventstream.EventCancel
	EventNotification = eventstream.EventNotification
)
View Source
const (
	MaxSemanticQueries       = 5
	MaxSemanticResultRows    = 200
	MaxSemanticMeasures      = 20
	MaxSemanticFilters       = 20
	MaxSemanticFilterValues  = 20
	MaxSemanticFilterBytes   = 256
	MaxSemanticDateRangeDays = 3660
)
View Source
const DefaultAnalyticsProcessMaxListeners = 4096
View Source
const DefaultAnalyticsQueueAdmissionBytes uint64 = 512 << 20
View Source
const DefaultListenerQueueBytes = 16 << 20
View Source
const DefaultListenerQueueSize = 16
View Source
const DefaultMaxListeners = 128
View Source
const DefaultRealtimeListenerQueueBytes = 16 << 20
View Source
const DefaultRealtimeListenerQueueSize = 8
View Source
const MaxAnalyticsProcessListeners = 65536
View Source
const MaxAnalyticsQueueAdmissionBytes uint64 = 4 << 30
View Source
const MaxListenerQueueSize = 64

MaxListenerQueueSize bounds the number of events a listener may retain. Event payloads are already bounded by the underlying EventBus configuration.

Variables

View Source
var ErrAnalyticsListenerBudgetInvalid = errors.New("analytics process listener limit must be between 1 and 65536")
View Source
var ErrAnalyticsQueueBudgetInvalid = errors.New("analytics process queue admission budget must be between 1 byte and 4 GiB")
View Source
var ErrEventTooLarge = errors.New("analytics: event exceeds configured byte limit")
View Source
var ErrListenerLimit = fmt.Errorf("event bus listener limit reached")
View Source
var ErrRebuildLeaseLost = fmt.Errorf("analytics rebuild lease lost")

Functions

func AddReportModels

func AddReportModels(catalog *SemanticCatalog, reports []ReportDefinition) error

AddReportModels adds explicitly configured business models to a catalog. This lets a report expose a parent/child concept without making every child DocType an independent analytics dataset.

func Backfill

func Backfill(ctx context.Context, db *sql.DB, dialect kdb.Dialect, siteName string, registry *doctype.Registry, from time.Time, doctypeName string) (int, error)

Backfill runs the rebuild under ctx so shutdown/deadline cancellation can release the tenant rebuild lock and leave prior rollups intact.

func BootstrapTables

func BootstrapTables(ctx context.Context, database *sql.DB, dialect db.SchemaDialect) error

BootstrapTables creates the analytics schema using the caller's cancellation and deadline. Engine startup passes its tenant work admission context here so schema work participates in the same bounded database-work budget as requests and workers.

func CreateRebuildJob

func CreateRebuildJob(db *sql.DB, dialect kdb.Dialect, job *RebuildJob) error

func MarkPublishedProjectionStale

func MarkPublishedProjectionStale(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site string, definition contract.ProjectionDefinition, scope contract.BusinessScope, sourceID string) error

MarkPublishedProjectionStale preserves the most recent output while making provider outages and unavailable sources visible to consumers.

func MigrateRollupMetrics

func MigrateRollupMetrics(db *sql.DB, dialect kdb.Dialect, 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 SavePublishedProjection

func SavePublishedProjection(ctx context.Context, database *sql.DB, dialect kdb.Dialect, snapshot PublishedProjectionSnapshot) error

SavePublishedProjection atomically publishes a complete revision. A failed save leaves the previous provider revision available to report consumers.

func SendCloudProductEvent

func SendCloudProductEvent(client *http.Client, cfg CloudRelayConfig, event CloudProductEventDTO, dedupeKey string)

func ValidateReportModels

func ValidateReportModels(registry *doctype.Registry, reports []ReportDefinition) error

ValidateReportModels verifies configured relationships and fields against the live DocType registry before those models are exposed or queried.

func WALHasPending

func WALHasPending(dir string) (bool, error)

WALHasPending reports whether the durable current or rotated WAL contains bytes awaiting worker replay. A stat/read failure is returned so callers do not silently treat an unreadable WAL as empty.

Types

type ChangeEvent

type ChangeEvent = eventstream.ChangeEvent

type CloudProductEventDTO

type CloudProductEventDTO struct {
	SiteID     string `json:"site_id"`
	AccountID  string `json:"account_id"`
	Kind       string `json:"kind"`
	Properties any    `json:"properties,omitempty"`
}

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) EnqueueProductEvent

func (r *CloudRelay) EnqueueProductEvent(event CloudProductEventDTO, dedupeKey string) bool

EnqueueProductEvent adds optional Cloud telemetry to the tenant-owned relay worker. It never performs network I/O on the caller's request path. The bounded queue drops excess or oversized telemetry rather than delaying tenant operations.

func (*CloudRelay) ProductEventQueueSnapshot

func (r *CloudRelay) ProductEventQueueSnapshot() ProductEventQueueSnapshot

func (*CloudRelay) ProductEventsDropped

func (r *CloudRelay) ProductEventsDropped() uint64

ProductEventsDropped reports optional telemetry events discarded because they exceeded the payload limit or the bounded queue was full.

func (*CloudRelay) Start

func (r *CloudRelay) Start()

func (*CloudRelay) Stop

func (r *CloudRelay) Stop()

type CloudRelayConfig

type CloudRelayConfig struct {
	EventsURL   string
	SiteID      string
	AccountID   string
	EventsToken string
}

func LoadCloudRelayConfig

func LoadCloudRelayConfig() *CloudRelayConfig

type Config

type Config struct {
	ChannelSize    int    // event bus buffer capacity (default 1000)
	MaxEventBytes  int    // maximum encoded event size (default 1 MiB)
	MaxQueuedBytes int    // maximum serialized-payload budget for the in-memory wake-up queue (default 64 MiB)
	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"
)

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) []DataPointSpec

BuildDataPointCatalog returns the generic data points implied by a DocType.

type DerivedMetric

type DerivedMetric struct {
	Name    string `json:"name" yaml:"name"`
	Label   string `json:"label" yaml:"label"`
	Formula string `json:"formula" yaml:"formula"`
	Format  string `json:"format,omitempty" yaml:"format,omitempty"`
}

type DropCauseSnapshot

type DropCauseSnapshot struct {
	PayloadRejected                 int64
	WALWriteFailures                int64
	SubscriberOverflows             int64
	SubscriberRegistrationsRejected int64
}

DropCauseSnapshot keeps durable publication failures distinct from optional in-memory wake-up queue behavior. Counts are cumulative for this bus instance.

type EventBus

type EventBus = eventstream.Bus

func NewChannelBus

func NewChannelBus(capacity int, walDir string) EventBus

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.

func NewChannelBusWithLimits

func NewChannelBusWithLimits(capacity, maxEventBytes, maxQueuedBytes int, walDir string) EventBus

NewChannelBusWithLimits bounds the wake-up channel by both event count and the maximum encoded payload bytes it may retain. The WAL remains the durable queue, so reducing the in-memory hint capacity cannot lose published work.

func NewChannelBusWithMaxEventBytes

func NewChannelBusWithMaxEventBytes(capacity, maxEventBytes int, walDir string) EventBus

NewChannelBusWithMaxEventBytes creates an analytics bus that rejects an event before WAL publication when its encoded payload exceeds maxEventBytes.

type EventOp

type EventOp = eventstream.EventOp

Runtime event types are aliased here for source compatibility. New persistence, routing, and transport code should depend on eventstream.

type EventWALAcknowledger

type EventWALAcknowledger = eventstream.WALAcknowledger

type FirstDocTypePropertiesDTO

type FirstDocTypePropertiesDTO struct {
	DocType string `json:"doctype"`
	Site    string `json:"site"`
	Status  string `json:"status"`
}

type FirstLoginPropertiesDTO

type FirstLoginPropertiesDTO struct {
	User  string `json:"user"`
	Site  string `json:"site"`
	Login string `json:"login"`
}

type FirstRecordPropertiesDTO

type FirstRecordPropertiesDTO struct {
	DocType    string `json:"doctype"`
	DocName    string `json:"doc_name"`
	Operation  string `json:"operation"`
	ModifiedBy string `json:"modified_by"`
	Site       string `json:"site"`
}

type ListenerQueueSnapshot

type ListenerQueueSnapshot struct {
	Listeners       int
	MaxListeners    int
	QueuedItems     int
	UpperBoundBytes int
	MaxQueuedBytes  int
	// OldestAge is a conservative upper bound while this queue is nonempty.
	OldestAge time.Duration
}

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

func GenerateMetrics(dt *doctype.DocType) []*Metric

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"
	MetricSumByField         MetricType = "sum_by_field"
	MetricAvg                MetricType = "avg"
	MetricStateDistribution  MetricType = "state_distribution"
	MetricCountByLinkedField MetricType = "count_by_linked_field"
)

type ModelQuery

type ModelQuery struct {
	Model      string           `json:"model"`
	Measures   []string         `json:"measures"`
	Dimensions []string         `json:"dimensions,omitempty"`
	Filters    []SemanticFilter `json:"filters,omitempty"`
}

type MultiBus

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

MultiBus wraps an EventBus and is its sole subscriber, fanning each event out to independent listeners. Consumers should subscribe through MultiBus rather than competing to read from the inner channel.

func NewDeferredMultiBus

func NewDeferredMultiBus(inner EventBus) (*MultiBus, error)

NewDeferredMultiBus prepares a fan-out wrapper without starting a goroutine. The owner calls Start when its process or tenant generation becomes active.

func NewMultiBus

func NewMultiBus(inner EventBus) (*MultiBus, error)

NewMultiBus creates and starts a fan-out wrapper around an existing EventBus.

func (*MultiBus) AcknowledgeWAL

func (mb *MultiBus) AcknowledgeWAL(ids []string) error

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; the caller must only receive from it and must not send to or close it.

func (*MultiBus) AddRealtimeListener

func (mb *MultiBus) AddRealtimeListener(ch chan ChangeEvent) error

AddRealtimeListener registers a bounded local realtime queue. If it falls behind, MultiBus closes and removes it so the stream handler can reconnect and the client can refetch authorized state.

func (*MultiBus) Close

func (mb *MultiBus) Close() error

Close shuts down the fan-out and closes the inner bus.

func (*MultiBus) CommitWALRotation

func (mb *MultiBus) CommitWALRotation(path string) error

func (*MultiBus) DrainWAL

func (mb *MultiBus) DrainWAL(handler func(ChangeEvent)) (int, error)

func (*MultiBus) DrainWALBatch

func (mb *MultiBus) DrainWALBatch(limit int, handler func(ChangeEvent)) (int, error)

func (*MultiBus) DropCauses

func (mb *MultiBus) DropCauses() DropCauseSnapshot

func (*MultiBus) Dropped

func (mb *MultiBus) Dropped() int64

Dropped returns the number of fan-out events dropped for slow listeners.

func (*MultiBus) Inner

func (mb *MultiBus) Inner() EventBus

Inner returns the wrapped EventBus.

func (*MultiBus) ListenerCount

func (mb *MultiBus) ListenerCount() int

ListenerCount returns the number of listeners.

func (*MultiBus) ListenerLimit

func (mb *MultiBus) ListenerLimit() int

func (*MultiBus) ListenerQueueBudget

func (mb *MultiBus) ListenerQueueBudget() ListenerQueueSnapshot

func (*MultiBus) ListenerQueueCapacity

func (mb *MultiBus) ListenerQueueCapacity(realtime bool) int

ListenerQueueCapacity derives a conservative event count from the largest event accepted by the wrapped durable bus and this listener's byte budget.

func (*MultiBus) NewListenerQueue

func (mb *MultiBus) NewListenerQueue(realtime bool) chan ChangeEvent

func (*MultiBus) Publish

func (mb *MultiBus) Publish(event ChangeEvent) error

func (*MultiBus) QueueBudget

func (mb *MultiBus) QueueBudget() QueueBudgetSnapshot

QueueBudget exposes the wrapped durable bus's bounded in-memory queue estimate when that implementation supports it.

func (*MultiBus) RemoveListener

func (mb *MultiBus) RemoveListener(ch chan ChangeEvent)

RemoveListener removes a subscriber channel.

func (*MultiBus) RotateWAL

func (mb *MultiBus) RotateWAL() (string, error)

func (*MultiBus) SetMaxListeners

func (mb *MultiBus) SetMaxListeners(limit int) error

SetMaxListeners configures the subscriber count bound before listeners are registered. It is primarily used by tenant assembly and tests.

func (*MultiBus) SetQueueAdmission

func (mb *MultiBus) SetQueueAdmission(admission *QueueAdmission) error

SetQueueAdmission attaches the process-shared subscriber byte budget before fanout starts or listeners are registered.

func (*MultiBus) Start

func (mb *MultiBus) Start() error

Start launches the single owned fan-out reader exactly once.

func (*MultiBus) Subscribe

func (mb *MultiBus) Subscribe() (<-chan ChangeEvent, error)

Subscribe registers a buffered listener. Long-lived consumers should remove their listener explicitly when their context ends.

func (*MultiBus) TryAddListener

func (mb *MultiBus) TryAddListener(ch chan ChangeEvent) error

TryAddListener registers a listener or returns a capacity/closed error. On error the supplied channel is closed and is not owned by the bus.

type ProductEventQueueSnapshot

type ProductEventQueueSnapshot struct {
	Queued   int
	Capacity int
	Dropped  uint64
}

type ProjectionActorScope

type ProjectionActorScope struct {
	SubjectID      string
	OwnerOnly      bool
	OwnerField     string
	AssignedFields []string
}

ProjectionActorScope is derived from verified API authorization. Assignment and owner predicates are applied before report filters, aggregation, and row limits so analytics cannot widen actor visibility.

type PublishedProjectionSnapshot

type PublishedProjectionSnapshot struct {
	Site           string
	Definition     contract.ProjectionDefinition
	Scope          contract.BusinessScope
	SourceID       string
	SourceRevision string
	Cursor         string
	AsOf           time.Time
	Freshness      contract.QueryFreshness
	Data           json.RawMessage
}

PublishedProjectionSnapshot is an immutable, provider-revision-pinned projection value persisted in the analytics database. It shares the tenant rebuild lock with rollup backfills, so a reader never sees a partial rebuild.

func LoadPublishedProjection

func LoadPublishedProjection(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site string, definition contract.ProjectionDefinition, scope contract.BusinessScope, sourceID string) (PublishedProjectionSnapshot, error)

LoadPublishedProjection returns the latest authorized-scope snapshot for a source. Provider unavailability does not erase retained historical output.

func (PublishedProjectionSnapshot) Validate

func (s PublishedProjectionSnapshot) Validate() error

type PublishedProjectionStore

type PublishedProjectionStore struct {
	DB      *sql.DB
	Dialect kdb.Dialect
	Site    string
}

PublishedProjectionStore binds projection access to one tenant database.

func (PublishedProjectionStore) Load

func (PublishedProjectionStore) MarkStale

func (PublishedProjectionStore) Save

type QueryEngine

type QueryEngine struct {
	DB                    *sql.DB
	SiteName              string
	Dialect               kdb.Dialect
	BusinessScope         contract.BusinessScope
	ProjectionActorScopes map[string]ProjectionActorScope
	// contains filtered or unexported fields
}

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

func (qe *QueryEngine) ResolveInsights(doctype string, metrics []*Metric) (map[string]any, error)

ResolveInsights returns pre-computed numbers for a doctype — designed for AI consumption. Returns a flat map of metric_name → current value, plus trend indicators.

func (*QueryEngine) ResolveSemanticQuery

func (qe *QueryEngine) ResolveSemanticQuery(catalog *SemanticCatalog, request SemanticRequest, registries ...*doctype.Registry) (*SemanticQueryResponse, error)

ResolveSemanticQuery resolves the safe subset of semantic queries that can be served by the existing metric rollups. It intentionally refuses queries that would require an unsafe or ambiguous raw-table join.

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"
	Dimension string           `json:"dimension,omitempty"`
	Filters   []SemanticFilter `json:"filters,omitempty"`
	Limit     int              `json:"limit,omitempty"`
}

QueryRequest holds parameters for a metric query.

func (QueryRequest) Validate

func (req QueryRequest) Validate() error

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 QueryTime

type QueryTime struct {
	From        string `json:"from"`
	To          string `json:"to"`
	Granularity string `json:"granularity"`
}

type QueueAdmission

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

QueueAdmission bounds conservative queued-payload bytes across tenant wake-up channels and MultiBus listeners owned by one Engine process. Reservations use the configured maximum event size, not an estimate.

func NewAnalyticsQueueAdmission

func NewAnalyticsQueueAdmission(maxBytes uint64) (*QueueAdmission, error)

NewAnalyticsQueueAdmission returns a byte budget for queued analytics events with the default listener limit.

func NewAnalyticsQueueAdmissionWithLimits

func NewAnalyticsQueueAdmissionWithLimits(maxBytes uint64, maxListeners int) (*QueueAdmission, error)

NewAnalyticsQueueAdmissionWithLimits returns a budget of maxBytes queued bytes and maxListeners process listeners, or an error if either is out of range.

func (*QueueAdmission) Release

func (a *QueueAdmission) Release(bytes uint64)

Release returns bytes reserved by TryAcquire to the budget.

func (*QueueAdmission) ReleaseListener

func (a *QueueAdmission) ReleaseListener()

ReleaseListener releases one process-wide subscription slot.

func (*QueueAdmission) Snapshot

func (a *QueueAdmission) Snapshot() QueueSnapshot

Snapshot returns the current usage, limits and rejection counts.

func (*QueueAdmission) TryAcquire

func (a *QueueAdmission) TryAcquire(bytes uint64) bool

TryAcquire reserves bytes from the budget and reports whether they fit. A refusal is counted in the snapshot.

func (*QueueAdmission) TryAcquireListener

func (a *QueueAdmission) TryAcquireListener() bool

TryAcquireListener reserves one process-wide subscription slot.

type QueueBudgetSnapshot

type QueueBudgetSnapshot struct {
	QueuedItems     int
	MaxQueuedItems  int
	UpperBoundBytes int
	MaxQueuedBytes  int
	MaxEventBytes   int
	// OldestAge is a conservative upper bound because EventBus subscribers read
	// directly from the public channel and cannot report dequeue timestamps.
	OldestAge time.Duration
}

QueueBudgetSnapshot reports a conservative serialized-payload bound for the in-memory wake-up channel. Actual ChangeEvent object overhead is additional.

type QueueSnapshot

type QueueSnapshot struct {
	UsedBytes         uint64
	MaxBytes          uint64
	RejectedItems     uint64
	Listeners         int
	MaxListeners      int
	RejectedListeners uint64
}

QueueSnapshot is a point-in-time view of a QueueAdmission budget.

type RebuildJob

type RebuildJob struct {
	ID           string     `json:"id"`
	Site         string     `json:"-"`
	LeaseOwner   string     `json:"-"`
	FencingToken int64      `json:"-"`
	DocType      string     `json:"doctype,omitempty"`
	From         time.Time  `json:"-"`
	Status       string     `json:"status"`
	StartedAt    time.Time  `json:"started_at"`
	CompletedAt  *time.Time `json:"completed_at,omitempty"`
	Metrics      int        `json:"metrics,omitempty"`
	Error        string     `json:"error,omitempty"`
}

RebuildJob is the durable state of an administrator-triggered analytics rebuild.

func ClaimNextRebuildJob

func ClaimNextRebuildJob(ctx context.Context, database *sql.DB, dialect kdb.Dialect, site, owner string) (*RebuildJob, error)

ClaimNextRebuildJob transitions one queued or expired running job to running under a database-time lease. Each takeover increments its fencing token.

func GetRebuildJob

func GetRebuildJob(db *sql.DB, dialect kdb.Dialect, site, id string) (*RebuildJob, error)

type RebuildMetricsSnapshot

type RebuildMetricsSnapshot struct {
	Active, Claims, ClaimFailures, AdmissionDeferrals                    int64
	ExecutionFailures, LeaseRenewFailures, LeaseLost, CompletionFailures int64
}

RebuildMetricsSnapshot contains aggregate runner state without tenant or job identifiers, suitable for process-level resource telemetry.

type RebuildRunner

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

RebuildRunner processes persisted jobs for one tenant. The Engine runtime owns its Run goroutine; HTTP requests only persist work and call Notify.

func NewRebuildRunner

func NewRebuildRunner(database *sql.DB, dialect kdb.Dialect, site string, registry *doctype.Registry, admission interface {
	Acquire(context.Context) (func(), error)
}) *RebuildRunner

NewRebuildRunner constructs a bounded, single-worker tenant rebuild runner.

func (*RebuildRunner) MetricsSnapshot

func (r *RebuildRunner) MetricsSnapshot() RebuildMetricsSnapshot

func (*RebuildRunner) Notify

func (r *RebuildRunner) Notify()

Notify wakes the worker after a durable job insert. Polling remains the recovery mechanism for a crash between commit and notification.

func (*RebuildRunner) Run

func (r *RebuildRunner) Run(ctx context.Context)

Run processes one job at a time until its owning tenant runtime is canceled.

type ReportDefinition

type ReportDefinition struct {
	Name        string          `json:"name" yaml:"name"`
	Label       string          `json:"label" yaml:"label"`
	Route       string          `json:"route,omitempty" yaml:"route,omitempty"`
	Permissions []string        `json:"permissions,omitempty" yaml:"permissions,omitempty"`
	Models      []SemanticModel `json:"models,omitempty" yaml:"models,omitempty"`
	Queries     []ReportQuery   `json:"queries" yaml:"queries"`
	Derived     []DerivedMetric `json:"derived,omitempty" yaml:"derived,omitempty"`
	Visuals     []ReportVisual  `json:"visuals,omitempty" yaml:"visuals,omitempty"`
}

func GenerateDefaultReports

func GenerateDefaultReports(catalog *SemanticCatalog) []ReportDefinition

GenerateDefaultReports creates a small, governed overview report for every model that does not provide an explicit report definition. It uses only fields already exposed by the semantic catalog, so new config packs get a useful analytics entry point without inventing business meaning or SQL.

func ParseReportYAML

func ParseReportYAML(data []byte, source string) (*ReportDefinition, error)

ParseReportYAML parses one report definition from a configuration file. The report remains declarative: execution is still governed by the catalog.

func ParseReportsDirectory

func ParseReportsDirectory(path string) ([]ReportDefinition, error)

ParseReportsDirectory parses all YAML report definitions in a config pack. A missing reports directory is valid for packs that do not provide reports.

func (*ReportDefinition) Validate

func (r *ReportDefinition) Validate(catalog *SemanticCatalog) error

type ReportQuery

type ReportQuery struct {
	ID         string           `json:"id" yaml:"id"`
	Model      string           `json:"model" yaml:"model"`
	Measures   []string         `json:"measures" yaml:"measures"`
	Dimensions []string         `json:"dimensions,omitempty" yaml:"dimensions,omitempty"`
	Filters    []SemanticFilter `json:"filters,omitempty" yaml:"filters,omitempty"`
}

type ReportVisual

type ReportVisual struct {
	ID     string         `json:"id" yaml:"id"`
	Type   string         `json:"type" yaml:"type"`
	Source string         `json:"source" yaml:"source"`
	XField string         `json:"x_field,omitempty" yaml:"x_field,omitempty"`
	Series []VisualSeries `json:"series,omitempty" yaml:"series,omitempty"`
}

type RollupDefinition

type RollupDefinition struct {
	Name            string   `json:"name" yaml:"name"`
	Measures        []string `json:"measures" yaml:"measures"`
	Dimensions      []string `json:"dimensions,omitempty" yaml:"dimensions,omitempty"`
	TimeDimension   string   `json:"time_dimension,omitempty" yaml:"time_dimension,omitempty"`
	Granularity     string   `json:"granularity" yaml:"granularity"` // day, week, month, quarter, year
	RefreshInterval string   `json:"refresh_interval,omitempty" yaml:"refresh_interval,omitempty"`
	PartitionBy     string   `json:"partition_by,omitempty" yaml:"partition_by,omitempty"`
}

func (*RollupDefinition) Validate

func (r *RollupDefinition) Validate(measures, dimensions map[string]bool, modelTimeDimension string) error

type SemanticCatalog

type SemanticCatalog struct {
	Models  []SemanticModel    `json:"models" yaml:"models"`
	Reports []ReportDefinition `json:"reports,omitempty" yaml:"reports,omitempty"`
}

SemanticCatalog is the governed vocabulary exposed to report builders and other analytics consumers. It deliberately describes business concepts, rather than exposing arbitrary SQL or storage details.

func BuildSemanticCatalog

func BuildSemanticCatalog(docTypes []*doctype.DocType) *SemanticCatalog

BuildSemanticCatalog exposes the safe, automatically discoverable portion of the registry to analytics consumers.

func (*SemanticCatalog) Validate

func (c *SemanticCatalog) Validate() error

type SemanticDimension

type SemanticDimension struct {
	Name                   string   `json:"name" yaml:"name"`
	Label                  string   `json:"label" yaml:"label"`
	Field                  string   `json:"field" yaml:"field"`
	Type                   string   `json:"type" yaml:"type"` // category, time, number, boolean, text
	SupportedGranularities []string `json:"supported_granularities,omitempty" yaml:"supported_granularities,omitempty"`
	Source                 string   `json:"source,omitempty" yaml:"source,omitempty"` // parent or child for related models
	LinkDoctype            string   `json:"link_doctype,omitempty" yaml:"link_doctype,omitempty"`
	LinkLabelField         string   `json:"link_label_field,omitempty" yaml:"link_label_field,omitempty"`
}

type SemanticFilter

type SemanticFilter struct {
	Field    string   `json:"field" yaml:"field"`
	Operator string   `json:"operator" yaml:"operator"`
	Values   []string `json:"values" yaml:"values"`
}

type SemanticMeasure

type SemanticMeasure struct {
	Name        string           `json:"name" yaml:"name"`
	Label       string           `json:"label" yaml:"label"`
	Field       string           `json:"field,omitempty" yaml:"field,omitempty"`
	Aggregation string           `json:"aggregation" yaml:"aggregation"`           // count, sum, avg, min, max
	Format      string           `json:"format,omitempty" yaml:"format,omitempty"` // number, currency, percent
	Filters     []SemanticFilter `json:"filters,omitempty" yaml:"filters,omitempty"`
	Source      string           `json:"source,omitempty" yaml:"source,omitempty"` // parent or child for related models
}

type SemanticModel

type SemanticModel struct {
	Name                  string                     `json:"name" yaml:"name"`
	Label                 string                     `json:"label" yaml:"label"`
	Description           string                     `json:"description,omitempty" yaml:"description,omitempty"`
	SourceDoctype         string                     `json:"source_doctype,omitempty" yaml:"source_doctype,omitempty"`
	TimeDimension         string                     `json:"time_dimension,omitempty" yaml:"time_dimension,omitempty"`
	Dimensions            []SemanticDimension        `json:"dimensions,omitempty" yaml:"dimensions,omitempty"`
	Measures              []SemanticMeasure          `json:"measures,omitempty" yaml:"measures,omitempty"`
	Rollups               []RollupDefinition         `json:"rollups,omitempty" yaml:"rollups,omitempty"`
	Relation              *SemanticRelation          `json:"relation,omitempty" yaml:"relation,omitempty"`
	ProjectionOwner       string                     `json:"projection_owner,omitempty" yaml:"projection_owner,omitempty"`
	ProjectionID          string                     `json:"projection_id,omitempty" yaml:"projection_id,omitempty"`
	ProjectionOwnerField  string                     `json:"projection_owner_field,omitempty" yaml:"projection_owner_field,omitempty"`
	PublishedQuery        string                     `json:"published_query,omitempty" yaml:"published_query,omitempty"`
	ProjectionScopePolicy contract.ResourceScopeKind `json:"projection_scope_policy,omitempty" yaml:"projection_scope_policy,omitempty"`
	AllowedFields         []string                   `json:"allowed_fields,omitempty" yaml:"allowed_fields,omitempty"`
}

SemanticModel is an analytics-friendly projection of one or more sources.

func BuildPublishedProjectionModel

func BuildPublishedProjectionModel(name, label string, definition contract.ProjectionDefinition, dimensions []SemanticDimension, measures []SemanticMeasure) (SemanticModel, error)

BuildPublishedProjectionModel creates an analytics model backed only by a module projection. Its owner-controlled field allowlist is retained with the projection, so historical reports remain readable if an input source goes away.

func BuildPublishedSemanticModel

func BuildPublishedSemanticModel(name, label, owner, projection, query string, scopePolicy contract.ResourceScopeKind, fields []SemanticDimension, measures []SemanticMeasure) (SemanticModel, error)

BuildPublishedSemanticModel creates a reporting model solely from an owner's declared query output fields. It has no DocType/table source, so analytics execution cannot fall through to private record storage.

func BuildSemanticModel

func BuildSemanticModel(dt *doctype.DocType) SemanticModel

BuildSemanticModel creates a conservative catalog model from DocType metadata. Explicit semantic configuration can later enrich or replace this projection without changing the query contract.

func (*SemanticModel) Validate

func (m *SemanticModel) Validate() error

type SemanticQueryResponse

type SemanticQueryResponse struct {
	Queries     []SemanticQueryResult `json:"queries"`
	GeneratedAt string                `json:"generated_at"`
	DataSource  string                `json:"data_source"`
}

type SemanticQueryResult

type SemanticQueryResult struct {
	Model          string                  `json:"model"`
	Columns        []string                `json:"columns"`
	Rows           []map[string]any        `json:"rows"`
	Total          int                     `json:"total"`
	SourceRevision string                  `json:"source_revision,omitempty"`
	AsOf           *time.Time              `json:"as_of,omitempty"`
	Freshness      contract.QueryFreshness `json:"freshness,omitempty"`
}

type SemanticRelation

type SemanticRelation struct {
	ParentDoctype   string                   `json:"parent_doctype" yaml:"parent_doctype"`
	ChildDoctype    string                   `json:"child_doctype" yaml:"child_doctype"`
	ChildTableField string                   `json:"child_table_field" yaml:"child_table_field"`
	ParentTimeField string                   `json:"parent_time_field" yaml:"parent_time_field"`
	Filters         []SemanticRelationFilter `json:"filters,omitempty" yaml:"filters,omitempty"`
}

SemanticRelation describes a business-level parent/child source. Child DocTypes are not exposed as independent models; a report must explicitly declare the parent table field through which its rows are interpreted.

type SemanticRelationFilter

type SemanticRelationFilter struct {
	Source   string `json:"source" yaml:"source"` // parent or child
	Field    string `json:"field" yaml:"field"`
	Operator string `json:"operator" yaml:"operator"`
	Value    string `json:"value" yaml:"value"`
}

type SemanticRequest

type SemanticRequest struct {
	Queries []ModelQuery `json:"queries"`
	Time    QueryTime    `json:"time"`
	Limit   int          `json:"limit,omitempty"`
}

SemanticRequest is a catalog-only analytics query: one or more model queries over a time range, with an optional result row limit.

func (*SemanticRequest) Validate

func (q *SemanticRequest) Validate(catalog *SemanticCatalog) error

Validate checks the request against catalog and the query, measure, filter, range and row limits, returning the first violation.

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.

func GetStatus

func GetStatus(bus EventBus) *Status

GetStatus returns the current analytics pipeline status.

type VisualSeries

type VisualSeries struct {
	Field  string `json:"field" yaml:"field"`
	Label  string `json:"label" yaml:"label"`
	Type   string `json:"type,omitempty" yaml:"type,omitempty"`
	Format string `json:"format,omitempty" yaml:"format,omitempty"`
}

type WALBacklogSnapshot

type WALBacklogSnapshot struct {
	Pending    bool
	AgeKnown   bool
	OldestAge  time.Duration
	Bytes      int64
	BytesKnown bool
}

WALBacklogSnapshot describes durable records waiting for analytics commit. OldestAge is measured from the local persistence timestamp stored with each new WAL record; a file whose oldest record lacks a timestamp makes AgeKnown false.

func InspectWALBacklog

func InspectWALBacklog(dir string) (WALBacklogSnapshot, error)

InspectWALBacklog scans the first durable record in each WAL file. Records are appended in persistence-time order within a file, so the first record provides the oldest timestamp without decoding the full backlog. Legacy or corrupt first records remain pending and make the age unknown.

type WALBatchDrainer

type WALBatchDrainer interface {
	DrainWALBatch(limit int, handler func(ChangeEvent)) (int, error)
}

WALBatchDrainer reads at most limit events from durable local storage. A non-positive limit means all available events. Workers use this optional capability to bound per-batch memory while retaining the EventBus contract.

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() error

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

func (w *Worker) InvalidateMetrics(doctype string)

InvalidateMetrics clears cached metrics for a single doctype, forcing re-generation on the next event. Call after config activation/rollback/reload.

func (*Worker) SetWorkAdmission

func (w *Worker) SetWorkAdmission(admission interface {
	Acquire(context.Context) (func(), error)
})

SetWorkAdmission attaches the endpoint-shared active-work limiter. It must be called before the worker starts; each flush or maintenance operation acquires exactly one slot for its complete unit of database work.

func (*Worker) Start

func (w *Worker) Start()

Start consumes events until stopped. Use StartAsync for goroutine startup.

func (*Worker) StartAsync

func (w *Worker) StartAsync()

StartAsync marks the worker started before launching its goroutine so Stop can wait for its final flush before closing the database and event bus.

func (*Worker) StartAsyncContext

func (w *Worker) StartAsyncContext(parent context.Context)

StartAsyncContext runs the worker under ctx. Canceling ctx stops event consumption and runs a bounded final flush before the worker exits.

func (*Worker) Stop

func (w *Worker) Stop()

Stop signals the worker to flush and exit.

Jump to

Keyboard shortcuts

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