From f890f1d8b4b7c6589bc9d8d41eb8770714e613b4 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Fri, 1 Sep 2023 15:48:27 +0300 Subject: [PATCH] tracer: add missing UniqLabels function Signed-off-by: Vasiliy Tolstov --- tracer/tracer.go | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tracer/tracer.go b/tracer/tracer.go index 442113c9..b76401e0 100644 --- a/tracer/tracer.go +++ b/tracer/tracer.go @@ -3,6 +3,8 @@ package tracer // import "go.unistack.org/micro/v4/tracer" import ( "context" + "fmt" + "sort" "go.unistack.org/micro/v4/options" ) @@ -44,3 +46,36 @@ type Span interface { // Kind returns span kind Kind() SpanKind } + +// sort labels alphabeticaly by label name +type byKey []interface{} + +func (k byKey) Len() int { return len(k) / 2 } +func (k byKey) Less(i, j int) bool { return fmt.Sprintf("%s", k[i*2]) < fmt.Sprintf("%s", k[j*2]) } +func (k byKey) Swap(i, j int) { + k[i*2], k[j*2] = k[j*2], k[i*2] + k[i*2+1], k[j*2+1] = k[j*2+1], k[i*2+1] +} + +func UniqLabels(labels []interface{}) []interface{} { + if len(labels)%2 == 1 { + labels = labels[:len(labels)-1] + } + if len(labels) > 2 { + sort.Sort(byKey(labels)) + + idx := 0 + for { + if labels[idx] == labels[idx+2] { + copy(labels[idx:], labels[idx+2:]) + labels = labels[:len(labels)-2] + } else { + idx += 2 + } + if idx+2 >= len(labels) { + break + } + } + } + return labels +}