Use slice to store lexialicly orderd key value pairs

This commit is contained in:
Holger Obermaier 2023-09-19 14:48:11 +02:00
parent c87c77a810
commit 42a9423203
2 changed files with 37 additions and 12 deletions

View File

@ -130,9 +130,10 @@ func (r *HttpReceiver) ServerHttp(w http.ResponseWriter, req *http.Request) {
fields[string(key)] = value.Interface() fields[string(key)] = value.Interface()
} }
// Decode time stamp
t, err := d.Time(influx.Nanosecond, time.Time{}) t, err := d.Time(influx.Nanosecond, time.Time{})
if err != nil { if err != nil {
msg := "ServerHttp: Failed to decode time: " + err.Error() msg := "ServerHttp: Failed to decode time stamp: " + err.Error()
cclog.ComponentError(r.name, msg) cclog.ComponentError(r.name, msg)
http.Error(w, msg, http.StatusInternalServerError) http.Error(w, msg, http.StatusInternalServerError)
return return

View File

@ -2,6 +2,7 @@ package sinks
import ( import (
"bytes" "bytes"
"cmp"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -69,23 +70,46 @@ func (s *HttpSink) Write(m lp.CCMetric) error {
s.encoder.StartLine(m.Name()) s.encoder.StartLine(m.Name())
// copy tags and meta data which should be used as tags // copy tags and meta data which should be used as tags
tags := make(map[string]string) type key_value struct {
keys := make([]string, 0) key string
value string
}
key_value_store := make([]key_value, 0)
for key, value := range m.Tags() { for key, value := range m.Tags() {
keys = append(keys, key) key_value_store =
tags[key] = value append(
key_value_store,
key_value{
key: key,
value: value,
},
)
} }
for _, key := range s.config.MetaAsTags { for _, key := range s.config.MetaAsTags {
if value, ok := m.GetMeta(key); ok { if value, ok := m.GetMeta(key); ok {
keys = append(keys, key) key_value_store =
tags[key] = value append(
key_value_store,
key_value{
key: key,
value: value,
},
)
} }
} }
// Encode tags // Encode tags (they musts be in lexical order)
slices.Sort(keys) slices.SortFunc(
for _, key := range keys { key_value_store,
s.encoder.AddTag(key, tags[key]) func(a key_value, b key_value) int {
return cmp.Compare(a.key, b.key)
},
)
for i := range key_value_store {
s.encoder.AddTag(
key_value_store[i].key,
key_value_store[i].value,
)
} }
// Encode fields // Encode fields
@ -257,7 +281,7 @@ func NewHttpSink(name string, config json.RawMessage) (Sink, error) {
} }
// Configure influx line protocol encoder // Configure influx line protocol encoder
s.encoder.SetPrecision(influx.Second) s.encoder.SetPrecision(influx.Nanosecond)
return s, nil return s, nil
} }