StatusApp/server/cache.go

58 lines
1.3 KiB
Go

package server
import (
"time"
"status/check"
"status/db"
)
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"`
}
var dayAggregation map[string]map[time.Time]stat
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 {
if cached, ok := dayAggregation[serviceName][day]; ok {
return cached
}
entries := db.GetFromDB(serviceName, day.AddDate(0, 0, -1), day)
result := stat{
StartTime: day,
}
for _, v := range entries {
result.SampleCount++
result.TotalPing += v.Ping
switch v.Status {
case check.Online:
result.SuccessCount++
case check.Offline:
result.FailCount++
}
}
result.Summary = convertToResult(result.SuccessCount, result.SampleCount)
dayAggregation[serviceName][day] = result
return result
}
func today() time.Time {
now := time.Now()
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
}