Write device aliases as startup metadata
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -22,6 +23,7 @@ type writer interface {
|
||||
type Service struct {
|
||||
config config.Config
|
||||
deviceAliases map[string]string
|
||||
aliasRecords []model.Record
|
||||
influxClient writer
|
||||
input chan model.RawMessage
|
||||
received atomic.Uint64
|
||||
@@ -40,9 +42,11 @@ type Snapshot struct {
|
||||
}
|
||||
|
||||
func NewService(cfg config.Config, influxClient writer) *Service {
|
||||
normalizedAliases := normalizeDeviceAliases(cfg.DeviceAliases)
|
||||
return &Service{
|
||||
config: cfg,
|
||||
deviceAliases: normalizeDeviceAliases(cfg.DeviceAliases),
|
||||
deviceAliases: normalizedAliases,
|
||||
aliasRecords: buildAliasRecords(normalizedAliases),
|
||||
influxClient: influxClient,
|
||||
input: make(chan model.RawMessage, cfg.App.BufferSize),
|
||||
}
|
||||
@@ -63,7 +67,18 @@ func (service *Service) Run(ctx context.Context) error {
|
||||
ticker := time.NewTicker(service.config.App.FlushInterval.Duration)
|
||||
defer ticker.Stop()
|
||||
|
||||
batch := make([]model.Record, 0, service.config.App.BatchSize)
|
||||
batch := append(make([]model.Record, 0, service.config.App.BatchSize+len(service.aliasRecords)), service.aliasRecords...)
|
||||
if len(batch) > 0 {
|
||||
flushCtx, cancel := context.WithTimeout(ctx, service.config.App.FlushTimeout.Duration)
|
||||
err := service.flush(flushCtx, batch)
|
||||
cancel()
|
||||
if err != nil {
|
||||
slog.Error("failed to flush alias metadata to influx; will retry on next interval", "count", len(batch), "error", err)
|
||||
} else {
|
||||
batch = batch[:0]
|
||||
}
|
||||
}
|
||||
|
||||
var input <-chan model.RawMessage = service.input
|
||||
|
||||
for {
|
||||
@@ -204,3 +219,33 @@ func normalizeDeviceKey(value string) string {
|
||||
normalized = strings.Trim(normalized, "_")
|
||||
return normalized
|
||||
}
|
||||
|
||||
func buildAliasRecords(aliases map[string]string) []model.Record {
|
||||
if len(aliases) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
devices := make([]string, 0, len(aliases))
|
||||
for device := range aliases {
|
||||
devices = append(devices, device)
|
||||
}
|
||||
sort.Strings(devices)
|
||||
|
||||
timestamp := time.Now().UTC()
|
||||
records := make([]model.Record, 0, len(devices))
|
||||
for _, device := range devices {
|
||||
records = append(records, model.Record{
|
||||
Measurement: "tasmota_device_meta",
|
||||
Tags: map[string]string{
|
||||
"device": device,
|
||||
"source": "config",
|
||||
},
|
||||
Fields: map[string]any{
|
||||
"device_alias": aliases[device],
|
||||
},
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
return records
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user