telemetry

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package telemetry collects and publishes operational metrics via MQTT for Home Assistant sensor integration. Metrics include system health (DB sizes), token usage, active sessions, request performance, loop states, and attachment store statistics.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArchiveSource

type ArchiveSource interface {
	ActiveSessionCount() (int, error)
}

ArchiveSource provides active session counts for telemetry without coupling this package to the full memory package.

type AttachmentSource

type AttachmentSource interface {
	TelemetryStats(ctx context.Context) (total, totalBytes, unique int64, err error)
}

AttachmentSource provides aggregate attachment statistics without coupling this package to the full attachments package.

type Collector

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

Collector aggregates operational metrics from multiple subsystems. All collection methods are safe for concurrent use — each call produces an independent Metrics snapshot.

func NewCollector

func NewCollector(src Sources) *Collector

NewCollector creates a Collector backed by the given sources.

func (*Collector) Collect

func (c *Collector) Collect(ctx context.Context) *Metrics

Collect gathers a point-in-time snapshot of all operational metrics. Individual subsystem failures are logged and result in zero values for the affected metrics — collection never returns an error.

type LoopMetric

type LoopMetric struct {
	Name       string
	State      string
	Iterations int
}

LoopMetric captures the state and iteration count for a single registered loop.

type MQTTPublisher

type MQTTPublisher interface {
	PublishDynamicState(ctx context.Context, entitySuffix, state string, attrJSON []byte) error
	RegisterSensors(sensors []mqtt.DynamicSensor)
}

MQTTPublisher is the subset of mqtt.Publisher used by the telemetry publisher. Defined as an interface for testability.

type Metrics

type Metrics struct {
	CollectedAt time.Time

	// System health — database file sizes in bytes.
	DBSizes map[string]int64

	// Token usage (24h rolling window).
	TokensInput   int64
	TokensOutput  int64
	TokensCost    float64
	TokensByModel map[string]ModelTokens

	// Sessions & context.
	ActiveSessions     int
	ContextUtilization float64 // 0–100 percentage

	// Request performance (24h rolling window).
	Requests24h  int
	Errors24h    int
	LatencyP50Ms float64
	LatencyP95Ms float64

	// Loop aggregate counts.
	LoopsActive   int
	LoopsSleeping int
	LoopsErrored  int
	LoopsTotal    int
	LoopDetails   []LoopMetric

	// Attachment store.
	AttachmentsTotal      int64
	AttachmentsTotalBytes int64
	AttachmentsUnique     int64
}

Metrics holds a point-in-time snapshot of all collected operational metrics. The zero value is safe — nil maps and zero counts produce valid (empty) sensor states.

type ModelTokens

type ModelTokens struct {
	Input  int64   `json:"input"`
	Output int64   `json:"output"`
	Cost   float64 `json:"cost"`
}

ModelTokens holds per-model token usage for the 24h window. Used as JSON attributes on the tokens_24h_cost sensor.

type Publisher

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

Publisher bridges collected metrics to MQTT state publishing. On each call to Publisher.Publish, it collects fresh metrics and publishes state values for every registered telemetry sensor. New loops discovered at publish time are registered as dynamic sensors automatically.

func NewPublisher

func NewPublisher(collector *Collector, mqttPub MQTTPublisher, builder *SensorBuilder, logger *slog.Logger) *Publisher

NewPublisher creates a telemetry publisher that collects metrics via the given collector and publishes them through the MQTT publisher.

func (*Publisher) Publish

func (p *Publisher) Publish(ctx context.Context) error

Publish collects a fresh metrics snapshot and publishes all sensor states to MQTT. Called by the mqtt-telemetry loop handler on each iteration.

type SensorBuilder

type SensorBuilder struct {
	InstanceID        string
	Prefix            string // HA object_id prefix, e.g. "aimee_thane_"
	StateTopicFn      func(string) string
	AttributesTopicFn func(string) string
	AvailabilityTopic string
	Device            mqtt.DeviceInfo
}

SensorBuilder constructs Home Assistant MQTT sensor definitions for telemetry metrics. It uses topic and device info from the MQTT publisher to produce correctly namespaced discovery payloads.

func (*SensorBuilder) LoopSensors

func (b *SensorBuilder) LoopSensors(loopName string) []mqtt.DynamicSensor

LoopSensors returns sensor definitions for a single named loop. Two sensors per loop: state (enum) and iterations (measurement). Loop names are sanitized to avoid MQTT topic separator conflicts.

func (*SensorBuilder) StaticSensors

func (b *SensorBuilder) StaticSensors() []mqtt.DynamicSensor

StaticSensors returns all telemetry sensor definitions to register with the MQTT publisher via mqtt.Publisher.RegisterSensors. These are the fixed sensors — per-loop sensors are registered dynamically as loops appear.

type Sources

type Sources struct {
	LoopRegistry     *loop.Registry
	UsageStore       *usage.Store
	ArchiveStore     ArchiveSource
	LogsDB           *sql.DB
	AttachmentSource AttachmentSource
	DBPaths          map[string]string // name → file path for os.Stat
	Logger           *slog.Logger
}

Sources holds references to all subsystems that provide telemetry data. Nil sources are handled gracefully — the corresponding metrics are reported as zero.

Jump to

Keyboard shortcuts

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