]> git.r.bdr.sh - rbdr/mobius/blob - hotline/stats.go
Add support for trackers that require a password
[rbdr/mobius] / hotline / stats.go
1 package hotline
2
3 import (
4 "sync"
5 "time"
6 )
7
8 // Stat counter keys
9 const (
10 StatCurrentlyConnected = iota
11 StatDownloadsInProgress
12 StatUploadsInProgress
13 StatWaitingDownloads
14 StatConnectionPeak
15 StatConnectionCounter
16 StatDownloadCounter
17 StatUploadCounter
18 )
19
20 type Counter interface {
21 Increment(keys ...int)
22 Decrement(key int)
23 Set(key, val int)
24 Get(key int) int
25 Values() map[string]interface{}
26 }
27
28 type Stats struct {
29 stats map[int]int
30 since time.Time
31
32 mu sync.RWMutex
33 }
34
35 func NewStats() *Stats {
36 return &Stats{
37 since: time.Now(),
38 stats: map[int]int{
39 StatCurrentlyConnected: 0,
40 StatDownloadsInProgress: 0,
41 StatUploadsInProgress: 0,
42 StatWaitingDownloads: 0,
43 StatConnectionPeak: 0,
44 StatDownloadCounter: 0,
45 StatUploadCounter: 0,
46 StatConnectionCounter: 0,
47 },
48 }
49 }
50
51 func (s *Stats) Increment(keys ...int) {
52 s.mu.Lock()
53 defer s.mu.Unlock()
54
55 for _, key := range keys {
56 s.stats[key]++
57 }
58 }
59
60 func (s *Stats) Decrement(key int) {
61 s.mu.Lock()
62 defer s.mu.Unlock()
63
64 s.stats[key]--
65 }
66
67 func (s *Stats) Set(key, val int) {
68 s.mu.Lock()
69 defer s.mu.Unlock()
70
71 s.stats[key] = val
72 }
73
74 func (s *Stats) Get(key int) int {
75 s.mu.RLock()
76 defer s.mu.RUnlock()
77
78 return s.stats[key]
79 }
80
81 func (s *Stats) Values() map[string]interface{} {
82 s.mu.RLock()
83 defer s.mu.RUnlock()
84
85 return map[string]interface{}{
86 "CurrentlyConnected": s.stats[StatCurrentlyConnected],
87 "DownloadsInProgress": s.stats[StatDownloadsInProgress],
88 "UploadsInProgress": s.stats[StatUploadsInProgress],
89 "WaitingDownloads": s.stats[StatWaitingDownloads],
90 "ConnectionPeak": s.stats[StatConnectionPeak],
91 "ConnectionCounter": s.stats[StatConnectionCounter],
92 "DownloadCounter": s.stats[StatDownloadCounter],
93 "UploadCounter": s.stats[StatUploadCounter],
94 "Since": s.since,
95 }
96 }