Files
nixevol fe24a88bac feat: 统计页支持一年时段和按日趋势
在线人数在新的有效访问后尽快刷新,历史查询保留一年并画出每日连接数。
2026-09-28 11:08:28 +08:00

100 lines
1.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"strconv"
"sync"
"sync/atomic"
"time"
)
const maxRowsPerMinute = 20000
type hitKey struct {
minute int64
table string
sid string
}
type sessionAgg struct {
fp string
first, last int64
}
// Recorder 把瓦片请求去重成「分钟 × table × 会话」。Record 只碰内存。
type Recorder struct {
mu sync.Mutex
minute int64
seen map[hitKey]struct{}
pending []hitKey
sessions map[string]*sessionAgg
dropped atomic.Int64
}
func NewRecorder() *Recorder {
return &Recorder{
seen: make(map[hitKey]struct{}),
sessions: make(map[string]*sessionAgg),
}
}
func (r *Recorder) Record(now time.Time, table, sid, fp string) bool {
m := now.Unix() / 60
if sid == "" {
sid = "~" + fp + ":" + strconv.FormatInt(m, 10)
}
k := hitKey{m, table, sid}
r.mu.Lock()
defer r.mu.Unlock()
if m > r.minute {
r.minute = m
r.seen = make(map[hitKey]struct{})
}
if _, ok := r.seen[k]; ok {
return false
}
if len(r.seen) >= maxRowsPerMinute {
r.dropped.Add(1)
return false
}
r.seen[k] = struct{}{}
r.pending = append(r.pending, k)
s := r.sessions[sid]
if s == nil {
r.sessions[sid] = &sessionAgg{fp: fp, first: m, last: m}
return true
}
if m < s.first {
s.first = m
}
if m > s.last {
s.last = m
}
return true
}
func (r *Recorder) Snapshot() ([]hitKey, map[string]sessionAgg) {
r.mu.Lock()
defer r.mu.Unlock()
hits := append([]hitKey(nil), r.pending...)
sessions := make(map[string]sessionAgg, len(r.sessions))
for id, s := range r.sessions {
sessions[id] = *s
}
return hits, sessions
}
// Take 取走待写入的数据。写库失败时调用方丢弃这一批,不重试。
func (r *Recorder) Take() ([]hitKey, map[string]*sessionAgg) {
r.mu.Lock()
defer r.mu.Unlock()
hits, sessions := r.pending, r.sessions
r.pending = nil
r.sessions = make(map[string]*sessionAgg)
return hits, sessions
}
func (r *Recorder) Dropped() int64 {
return r.dropped.Load()
}