2018-02-19 04:26:01 +00:00
|
|
|
package counters
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"sync/atomic"
|
|
|
|
|
2019-07-28 03:46:19 +00:00
|
|
|
c "github.com/Azareal/Gosora/common"
|
2020-02-26 10:34:38 +00:00
|
|
|
qgen "github.com/Azareal/Gosora/query_gen"
|
2019-07-28 03:46:19 +00:00
|
|
|
"github.com/pkg/errors"
|
2018-02-19 04:26:01 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var TopicCounter *DefaultTopicCounter
|
|
|
|
|
|
|
|
type DefaultTopicCounter struct {
|
|
|
|
buckets [2]int64
|
|
|
|
currentBucket int64
|
|
|
|
|
|
|
|
insert *sql.Stmt
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTopicCounter() (*DefaultTopicCounter, error) {
|
2018-08-04 11:46:36 +00:00
|
|
|
acc := qgen.NewAcc()
|
2019-07-28 03:46:19 +00:00
|
|
|
co := &DefaultTopicCounter{
|
2018-02-19 04:26:01 +00:00
|
|
|
currentBucket: 0,
|
2020-02-26 10:34:38 +00:00
|
|
|
insert: acc.Insert("topicchunks").Columns("count,createdAt").Fields("?,UTC_TIMESTAMP()").Prepare(),
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
2021-05-03 00:36:29 +00:00
|
|
|
c.Tasks.FifteenMin.Add(co.Tick)
|
|
|
|
//c.Tasks.Sec.Add(co.Tick)
|
|
|
|
c.Tasks.Shutdown.Add(co.Tick)
|
2019-07-28 03:46:19 +00:00
|
|
|
return co, acc.FirstError()
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2021-04-27 10:20:26 +00:00
|
|
|
func (co *DefaultTopicCounter) Tick() (e error) {
|
2019-07-28 03:46:19 +00:00
|
|
|
oldBucket := co.currentBucket
|
2018-02-19 04:26:01 +00:00
|
|
|
var nextBucket int64 // 0
|
2019-07-28 03:46:19 +00:00
|
|
|
if co.currentBucket == 0 {
|
2018-02-19 04:26:01 +00:00
|
|
|
nextBucket = 1
|
|
|
|
}
|
2019-07-28 03:46:19 +00:00
|
|
|
atomic.AddInt64(&co.buckets[oldBucket], co.buckets[nextBucket])
|
|
|
|
atomic.StoreInt64(&co.buckets[nextBucket], 0)
|
|
|
|
atomic.StoreInt64(&co.currentBucket, nextBucket)
|
|
|
|
|
|
|
|
previousViewChunk := co.buckets[oldBucket]
|
|
|
|
atomic.AddInt64(&co.buckets[oldBucket], -previousViewChunk)
|
2021-04-27 10:20:26 +00:00
|
|
|
e = co.insertChunk(previousViewChunk)
|
|
|
|
if e != nil {
|
|
|
|
return errors.Wrap(errors.WithStack(e), "topics counter")
|
2019-07-28 03:46:19 +00:00
|
|
|
}
|
|
|
|
return nil
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-07-28 03:46:19 +00:00
|
|
|
func (co *DefaultTopicCounter) Bump() {
|
|
|
|
atomic.AddInt64(&co.buckets[co.currentBucket], 1)
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|
|
|
|
|
2019-07-28 03:46:19 +00:00
|
|
|
func (co *DefaultTopicCounter) insertChunk(count int64) error {
|
2018-02-19 04:26:01 +00:00
|
|
|
if count == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
2019-07-28 03:46:19 +00:00
|
|
|
c.DebugLogf("Inserting a topicchunk with a count of %d", count)
|
2021-04-27 10:20:26 +00:00
|
|
|
_, e := co.insert.Exec(count)
|
|
|
|
return e
|
2018-02-19 04:26:01 +00:00
|
|
|
}
|