1
0
mirror of https://github.com/golang/go synced 2024-11-05 17:26:11 -07:00
go/internal/event/export/metric/exporter.go
Ian Cottrell c81623a0cb internal/event: move event/core.Tag to event/label.Label
Also moves core.Key to label.Key, but leaves the implementations
behind for now.
After using for a while, the word Tag conveys slightly the wrong
concept, tagging implies the entire set of information, label maps
better to a single named piece of information.
A label is just a named key/value pair, it is not really tied to the
event package, separating it makes it much easier to understand the
public symbols of the event and core packages, and allows us to also
move the key implementations somewhere else, which otherwise dominate
the API.

Change-Id: I46275d531cec91e28af6ab1e74a2713505d52533
Reviewed-on: https://go-review.googlesource.com/c/tools/+/229239
Run-TryBot: Ian Cottrell <iancottrell@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2020-04-23 18:13:33 +00:00

58 lines
1.4 KiB
Go

// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package metric aggregates events into metrics that can be exported.
package metric
import (
"context"
"sync"
"time"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/event/core"
"golang.org/x/tools/internal/event/label"
)
var Entries = core.NewKey("metric_entries", "The set of metrics calculated for an event")
type Config struct {
subscribers map[interface{}][]subscriber
}
type subscriber func(time.Time, label.Map, label.Label) Data
func (e *Config) subscribe(key label.Key, s subscriber) {
if e.subscribers == nil {
e.subscribers = make(map[interface{}][]subscriber)
}
e.subscribers[key] = append(e.subscribers[key], s)
}
func (e *Config) Exporter(output event.Exporter) event.Exporter {
var mu sync.Mutex
return func(ctx context.Context, ev core.Event, lm label.Map) context.Context {
if !ev.IsRecord() {
return output(ctx, ev, lm)
}
mu.Lock()
defer mu.Unlock()
var metrics []Data
for index := 0; ev.Valid(index); index++ {
l := ev.Label(index)
if !l.Valid() {
continue
}
id := l.Key()
if list := e.subscribers[id]; len(list) > 0 {
for _, s := range list {
metrics = append(metrics, s(ev.At, lm, l))
}
}
}
lm = label.MergeMaps(label.NewMap(Entries.Of(metrics)), lm)
return output(ctx, ev, lm)
}
}