2018-02-19 04:26:01 +00:00
|
|
|
package counters
|
|
|
|
|
|
|
|
import "database/sql"
|
|
|
|
import ".."
|
|
|
|
import "../../query_gen/lib"
|
|
|
|
|
|
|
|
var RouteViewCounter *DefaultRouteViewCounter
|
|
|
|
|
|
|
|
// TODO: Make this lockless?
|
|
|
|
type DefaultRouteViewCounter struct {
|
2018-03-08 03:59:47 +00:00
|
|
|
buckets []*RWMutexCounterBucket //[RouteID]count
|
|
|
|
insert *sql.Stmt
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewDefaultRouteViewCounter() (*DefaultRouteViewCounter, error) {
|
|
|
|
acc := qgen.Builder.Accumulator()
|
|
|
|
var routeBuckets = make([]*RWMutexCounterBucket, len(routeMapEnum))
|
|
|
|
for bucketID, _ := range routeBuckets {
|
|
|
|
routeBuckets[bucketID] = &RWMutexCounterBucket{counter: 0}
|
|
|
|
}
|
|
|
|
counter := &DefaultRouteViewCounter{
|
2018-03-08 03:59:47 +00:00
|
|
|
buckets: routeBuckets,
|
|
|
|
insert: acc.Insert("viewchunks").Columns("count, createdAt, route").Fields("?,UTC_TIMESTAMP(),?").Prepare(),
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
common.AddScheduledFifteenMinuteTask(counter.Tick) // There could be a lot of routes, so we don't want to be running this every second
|
|
|
|
//common.AddScheduledSecondTask(counter.Tick)
|
|
|
|
common.AddShutdownTask(counter.Tick)
|
|
|
|
return counter, acc.FirstError()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (counter *DefaultRouteViewCounter) Tick() error {
|
2018-03-08 03:59:47 +00:00
|
|
|
for routeID, routeBucket := range counter.buckets {
|
2018-02-19 04:26:01 +00:00
|
|
|
var count int
|
|
|
|
routeBucket.RLock()
|
|
|
|
count = routeBucket.counter
|
|
|
|
routeBucket.counter = 0
|
|
|
|
routeBucket.RUnlock()
|
|
|
|
|
|
|
|
err := counter.insertChunk(count, routeID) // TODO: Bulk insert for speed?
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (counter *DefaultRouteViewCounter) insertChunk(count int, route int) error {
|
|
|
|
if count == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var routeName = reverseRouteMapEnum[route]
|
|
|
|
common.DebugLogf("Inserting a viewchunk with a count of %d for route %s (%d)", count, routeName, route)
|
|
|
|
_, err := counter.insert.Exec(count, routeName)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (counter *DefaultRouteViewCounter) Bump(route int) {
|
|
|
|
// TODO: Test this check
|
2018-03-08 03:59:47 +00:00
|
|
|
common.DebugDetail("counter.buckets[", route, "]: ", counter.buckets[route])
|
|
|
|
if len(counter.buckets) <= route || route < 0 {
|
2018-02-19 04:26:01 +00:00
|
|
|
return
|
|
|
|
}
|
2018-03-08 03:59:47 +00:00
|
|
|
counter.buckets[route].Lock()
|
|
|
|
counter.buckets[route].counter++
|
|
|
|
counter.buckets[route].Unlock()
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|