File: stats.go

package info (click to toggle)
gitlab-shell 14.35.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,652 kB
  • sloc: ruby: 1,129; makefile: 583; sql: 391; sh: 384
file content (80 lines) | stat: -rw-r--r-- 1,690 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package command

import (
	"context"
	"sync"

	"github.com/sirupsen/logrus"
)

type requestStatsKey struct{}

// Stats records statistics about a command that was spawned.
type Stats struct {
	resource map[string]int
	metadata map[string]string
	sync.Mutex
}

// RecordSum sums up all the values for a given key.
func (stats *Stats) RecordSum(key string, value int) {
	stats.Lock()
	defer stats.Unlock()

	if prevValue, ok := stats.resource[key]; ok {
		value += prevValue
	}

	stats.resource[key] = value
}

// RecordMax will store the max value for a given key.
func (stats *Stats) RecordMax(key string, value int) {
	stats.Lock()
	defer stats.Unlock()

	if prevValue, ok := stats.resource[key]; ok {
		if prevValue > value {
			return
		}
	}

	stats.resource[key] = value
}

// RecordMetadata records metadata for the given key.
func (stats *Stats) RecordMetadata(key string, value string) {
	stats.Lock()
	defer stats.Unlock()

	stats.metadata[key] = value
}

// Fields returns all the stats as logrus.Fields
func (stats *Stats) Fields() logrus.Fields {
	stats.Lock()
	defer stats.Unlock()

	f := logrus.Fields{}
	for k, v := range stats.resource {
		f[k] = v
	}
	for k, v := range stats.metadata {
		f[k] = v
	}
	return f
}

// StatsFromContext gets the `Stats` from the given context.
func StatsFromContext(ctx context.Context) *Stats {
	stats, _ := ctx.Value(requestStatsKey{}).(*Stats)
	return stats
}

// InitContextStats returns a new context with `Stats` added to the given context.
func InitContextStats(ctx context.Context) context.Context {
	return context.WithValue(ctx, requestStatsKey{}, &Stats{
		resource: make(map[string]int),
		metadata: make(map[string]string),
	})
}