musiclink/internal/matrixbot/stats.go

100 lines
1.9 KiB
Go

package matrixbot
import (
"sync"
"sync/atomic"
"time"
)
type botStats struct {
received int64
responded int64
dropped int64
rateLimited int64
encryptedSkipped int64
mu sync.Mutex
lastEvent time.Time
lastSync time.Time
lastSend time.Time
lastSendError string
}
type statsSnapshot struct {
Received int64
Responded int64
Dropped int64
RateLimited int64
EncryptedSkipped int64
LastEvent time.Time
LastSync time.Time
LastSend time.Time
LastSendError string
}
func (s *botStats) markReceived() {
atomic.AddInt64(&s.received, 1)
s.setLastEvent(time.Now())
}
func (s *botStats) markResponded() {
atomic.AddInt64(&s.responded, 1)
s.setLastSend(time.Now())
}
func (s *botStats) markDropped() {
atomic.AddInt64(&s.dropped, 1)
}
func (s *botStats) markRateLimited() {
atomic.AddInt64(&s.rateLimited, 1)
}
func (s *botStats) markEncryptedSkipped() {
atomic.AddInt64(&s.encryptedSkipped, 1)
}
func (s *botStats) markSync() {
s.setLastSync(time.Now())
}
func (s *botStats) setLastEvent(t time.Time) {
s.mu.Lock()
s.lastEvent = t
s.mu.Unlock()
}
func (s *botStats) setLastSync(t time.Time) {
s.mu.Lock()
s.lastSync = t
s.mu.Unlock()
}
func (s *botStats) setLastSend(t time.Time) {
s.mu.Lock()
s.lastSend = t
s.mu.Unlock()
}
func (s *botStats) setLastSendError(err string) {
s.mu.Lock()
s.lastSendError = err
s.mu.Unlock()
}
func (s *botStats) Snapshot() statsSnapshot {
s.mu.Lock()
defer s.mu.Unlock()
return statsSnapshot{
Received: atomic.LoadInt64(&s.received),
Responded: atomic.LoadInt64(&s.responded),
Dropped: atomic.LoadInt64(&s.dropped),
RateLimited: atomic.LoadInt64(&s.rateLimited),
EncryptedSkipped: atomic.LoadInt64(&s.encryptedSkipped),
LastEvent: s.lastEvent,
LastSync: s.lastSync,
LastSend: s.lastSend,
LastSendError: s.lastSendError,
}
}