StatusApp/server/cache.go

61 lines
1.4 KiB
Go

2020-04-23 07:42:16 +07:00
package server
import (
"time"
2020-04-23 13:44:23 +07:00
"status/check"
2020-04-23 07:42:16 +07:00
"status/db"
)
2020-04-23 13:44:23 +07:00
type stat struct {
StartTime time.Time `json:"start_time"`
TotalPing int64 `json:"total_ping"`
SampleCount int `json:"sample_count"`
SuccessCount int `json:"success_count"`
FailCount int `json:"fail_count"`
Summary check.Result `json:"summary"`
}
2020-04-24 07:33:57 +07:00
var dayAggregation = make(map[string]map[time.Time]stat)
2020-04-23 13:44:23 +07:00
func convertToResult(successCount, totalCount int) check.Result {
if successCount >= totalCount*99/100 {
return check.Online
}
if successCount >= totalCount*9/10 {
return check.Unstable
}
return check.Offline
}
func getDay(serviceName string, day time.Time) stat {
2020-04-24 07:33:57 +07:00
if _, ok := dayAggregation[serviceName]; !ok {
dayAggregation[serviceName] = make(map[time.Time]stat)
}
2020-04-23 13:44:23 +07:00
if cached, ok := dayAggregation[serviceName][day]; ok {
return cached
}
entries := db.GetFromDB(serviceName, day.AddDate(0, 0, -1), day)
result := stat{
StartTime: day,
}
2020-04-23 07:42:16 +07:00
for _, v := range entries {
2020-04-23 13:44:23 +07:00
result.SampleCount++
result.TotalPing += v.Ping
switch v.Status {
case check.Online:
result.SuccessCount++
case check.Offline:
result.FailCount++
2020-04-23 07:42:16 +07:00
}
}
2020-04-23 13:44:23 +07:00
result.Summary = convertToResult(result.SuccessCount, result.SampleCount)
2020-04-23 14:51:45 +07:00
dayAggregation[serviceName][day] = result
2020-04-23 07:42:16 +07:00
return result
}
2020-04-23 13:44:23 +07:00
func today() time.Time {
now := time.Now()
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
}