RoadSign/pkg/navi/metrics.go

64 lines
1.5 KiB
Go
Raw Normal View History

2024-01-25 06:46:43 +00:00
package navi
import (
"github.com/spf13/viper"
"time"
)
2024-01-25 06:46:43 +00:00
2024-01-31 05:17:52 +00:00
type RoadMetrics struct {
Traces []RoadTrace `json:"-"`
Traffic map[string]int64 `json:"traffic"`
TrafficFrom map[string]int64 `json:"traffic_from"`
TotalTraffic int64 `json:"total_traffic"`
StartupAt time.Time `json:"startup_at"`
2024-01-31 05:17:52 +00:00
}
2024-01-25 06:46:43 +00:00
type RoadTrace struct {
Timestamp time.Time `json:"timestamp"`
2024-01-25 06:46:43 +00:00
Region string `json:"region"`
Location string `json:"location"`
Destination string `json:"destination"`
Uri string `json:"uri"`
IpAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
Error RoadTraceError `json:"error"`
}
type RoadTraceError struct {
IsNull bool `json:"is_null"`
Message string `json:"message"`
}
2024-01-31 05:17:52 +00:00
func (v *RoadMetrics) AddTrace(trace RoadTrace) {
2024-10-18 15:21:51 +00:00
if viper.GetBool("performance.low_memory") {
return
}
2024-01-31 05:17:52 +00:00
v.TotalTraffic++
trace.Timestamp = time.Now()
2024-01-31 05:17:52 +00:00
if _, ok := v.Traffic[trace.Region]; !ok {
v.Traffic[trace.Region] = 0
} else {
v.Traffic[trace.Region]++
}
if _, ok := v.TrafficFrom[trace.IpAddress]; !ok {
v.TrafficFrom[trace.IpAddress] = 0
} else {
v.TrafficFrom[trace.IpAddress]++
}
2024-01-25 06:46:43 +00:00
v.Traces = append(v.Traces, trace)
2024-01-31 05:17:52 +00:00
// Garbage recycle
if len(v.Traffic) > viper.GetInt("performance.traces_limit") {
2024-10-18 15:21:51 +00:00
clear(v.Traffic)
2024-01-31 05:17:52 +00:00
}
if len(v.TrafficFrom) > viper.GetInt("performance.traces_limit") {
2024-10-18 15:21:51 +00:00
clear(v.TrafficFrom)
2024-01-31 05:17:52 +00:00
}
2024-01-25 06:46:43 +00:00
if len(v.Traces) > viper.GetInt("performance.traces_limit") {
2024-10-18 15:21:51 +00:00
clear(v.Traces)
2024-01-25 06:46:43 +00:00
}
}