statping/hits.go

76 lines
1.5 KiB
Go
Raw Normal View History

2018-06-10 01:31:13 +00:00
package main
2018-06-22 04:02:57 +00:00
import (
2018-06-29 02:24:31 +00:00
"github.com/hunterlong/statup/log"
2018-06-22 04:02:57 +00:00
"time"
"upper.io/db.v3"
)
2018-06-10 01:31:13 +00:00
type Hit struct {
2018-06-15 04:30:10 +00:00
Id int `db:"id,omitempty"`
Service int64 `db:"service"`
Latency float64 `db:"latency"`
CreatedAt time.Time `db:"created_at"`
2018-06-10 01:31:13 +00:00
}
2018-06-22 04:02:57 +00:00
func hitCol() db.Collection {
return dbSession.Collection("hits")
}
2018-06-15 04:30:10 +00:00
func (s *Service) CreateHit(d HitData) (int64, error) {
h := Hit{
Service: s.Id,
Latency: d.Latency,
CreatedAt: time.Now(),
2018-06-11 03:41:02 +00:00
}
2018-06-22 04:02:57 +00:00
uuid, err := hitCol().Insert(h)
2018-06-15 04:30:10 +00:00
if uuid == nil {
2018-06-29 02:24:31 +00:00
log.Send(2, err)
2018-06-15 04:30:10 +00:00
return 0, err
2018-06-11 03:41:02 +00:00
}
2018-06-15 04:30:10 +00:00
return uuid.(int64), err
2018-06-11 03:41:02 +00:00
}
2018-06-15 04:30:10 +00:00
func (s *Service) Hits() ([]Hit, error) {
var hits []Hit
2018-06-22 04:02:57 +00:00
col := hitCol().Find("service", s.Id).OrderBy("-id")
err := col.All(&hits)
return hits, err
}
2018-06-24 11:51:07 +00:00
func (s *Service) LimitedHits() ([]*Hit, error) {
var hits []*Hit
col := hitCol().Find("service", s.Id).OrderBy("-id").Limit(1024)
2018-06-15 04:30:10 +00:00
err := col.All(&hits)
2018-06-24 11:51:07 +00:00
return reverseHits(hits), err
}
func reverseHits(input []*Hit) []*Hit {
if len(input) == 0 {
return input
}
return append(reverseHits(input[1:]), input[0])
2018-06-10 01:31:13 +00:00
}
2018-06-15 04:30:10 +00:00
func (s *Service) SelectHitsGroupBy(group string) ([]Hit, error) {
var hits []Hit
2018-06-22 04:02:57 +00:00
col := hitCol().Find("service", s.Id)
2018-06-15 04:30:10 +00:00
err := col.All(&hits)
return hits, err
2018-06-10 01:31:13 +00:00
}
2018-06-15 04:30:10 +00:00
func (s *Service) TotalHits() (uint64, error) {
2018-06-22 04:02:57 +00:00
col := hitCol().Find("service", s.Id)
2018-06-15 04:30:10 +00:00
amount, err := col.Count()
return amount, err
}
func (s *Service) Sum() (float64, error) {
2018-06-10 01:31:13 +00:00
var amount float64
2018-06-15 04:30:10 +00:00
hits, err := s.Hits()
for _, h := range hits {
amount += h.Latency
}
return amount, err
2018-06-10 01:31:13 +00:00
}