status-go/services/rpcstats/stats.go

60 lines
1.2 KiB
Go
Raw Permalink Normal View History

2021-03-08 11:18:43 +00:00
package rpcstats
import (
"sync"
)
type RPCUsageStats struct {
total uint
counterPerMethod *sync.Map
counterPerMethodPerTag *sync.Map
2021-03-08 11:18:43 +00:00
}
var stats *RPCUsageStats
var mu sync.Mutex
2021-03-08 11:18:43 +00:00
func getInstance() *RPCUsageStats {
mu.Lock()
defer mu.Unlock()
2021-03-08 11:18:43 +00:00
if stats == nil {
stats = &RPCUsageStats{}
stats.counterPerMethod = &sync.Map{}
stats.counterPerMethodPerTag = &sync.Map{}
2021-03-08 11:18:43 +00:00
}
return stats
}
func getStats() (uint, *sync.Map, *sync.Map) {
2021-03-08 11:18:43 +00:00
stats := getInstance()
return stats.total, stats.counterPerMethod, stats.counterPerMethodPerTag
2021-03-08 11:18:43 +00:00
}
func resetStats() {
stats := getInstance()
stats.total = 0
stats.counterPerMethod = &sync.Map{}
stats.counterPerMethodPerTag = &sync.Map{}
2021-03-08 11:18:43 +00:00
}
func CountCall(method string) {
stats := getInstance()
2021-03-08 11:18:43 +00:00
stats.total++
value, _ := stats.counterPerMethod.LoadOrStore(method, uint(0))
stats.counterPerMethod.Store(method, value.(uint)+1)
}
func CountCallWithTag(method string, tag string) {
if tag == "" {
CountCall(method)
return
}
stats := getInstance()
value, _ := stats.counterPerMethodPerTag.LoadOrStore(tag, &sync.Map{})
methodMap := value.(*sync.Map)
value, _ = methodMap.LoadOrStore(method, uint(0))
methodMap.Store(method, value.(uint)+1)
stats.total++
2021-03-08 11:18:43 +00:00
}