feat: 统计页支持一年时段和按日趋势

在线人数在新的有效访问后尽快刷新,历史查询保留一年并画出每日连接数。
This commit is contained in:
nixevol
2026-09-28 11:08:28 +08:00
parent 28170a7fe2
commit fe24a88bac
12 changed files with 358 additions and 36 deletions
+146 -7
View File
@@ -36,6 +36,17 @@ type rangeResp struct {
End string `json:"end"`
Total int `json:"total"`
Tables []tableCount `json:"tables"`
Daily []dayCount `json:"daily"`
}
type dayCount struct {
Date string `json:"date"`
Count int `json:"count"`
}
type dayRow struct {
day int64
sessionRow
}
type apiErr struct {
@@ -54,7 +65,7 @@ func errBadOrder() *apiErr {
}
func errTooLong() *apiErr {
return &apiErr{status: http.StatusBadRequest, Code: "range_too_long", Message: "时段不能超过 72 小时"}
return &apiErr{status: http.StatusBadRequest, Code: "range_too_long", Message: "时段不能超过 1 年"}
}
func errTooOld(earliest time.Time) *apiErr {
@@ -198,6 +209,48 @@ func (a *App) handleOnline(w http.ResponseWriter, r *http.Request) {
writeJSONBytes(w, http.StatusOK, body)
}
func (a *App) pokeOnline() {
select {
case a.onlinePoke <- struct{}{}:
default:
}
}
func mergePending(rows []sessionRow, hits []hitKey, sessions map[string]sessionAgg, from, to int64) []sessionRow {
index := make(map[[2]string]int, len(rows))
for i, row := range rows {
index[[2]string{row.table, row.sid}] = i
}
for _, hit := range hits {
if hit.minute < from || hit.minute > to {
continue
}
sess, ok := sessions[hit.sid]
if !ok {
continue
}
key := [2]string{hit.table, hit.sid}
if i, ok := index[key]; ok {
if sess.first < rows[i].first {
rows[i].first = sess.first
}
if sess.last > rows[i].last {
rows[i].last = sess.last
}
continue
}
rows = append(rows, sessionRow{
table: hit.table,
sid: hit.sid,
fp: sess.fp,
first: sess.first,
last: sess.last,
})
index[key] = len(rows) - 1
}
return rows
}
func (a *App) buildOnline(ctx context.Context, now time.Time) ([]byte, error) {
m := now.Unix() / 60
from := m - int64(a.cfg.OnlineMinutes)
@@ -205,6 +258,8 @@ func (a *App) buildOnline(ctx context.Context, now time.Time) ([]byte, error) {
if err != nil {
return nil, err
}
hits, sessions := a.rec.Snapshot()
rows = mergePending(rows, hits, sessions, from, m)
tables := sortedTables(estimate(rows).Tables)
return json.Marshal(onlineResp{
ServerTime: formatRFC3339(now),
@@ -218,13 +273,29 @@ func (a *App) loopOnline(ctx context.Context) {
if err := a.refreshOnline(context.Background()); err != nil {
slog.Error("在线统计失败", "err", err)
}
t := time.NewTicker(onlineRefreshEvery)
defer t.Stop()
expire := time.NewTicker(onlineRefreshEvery)
defer expire.Stop()
var debounce *time.Timer
var debounceC <-chan time.Time
for {
select {
case <-ctx.Done():
if debounce != nil {
debounce.Stop()
}
return
case <-t.C:
case <-expire.C:
if err := a.refreshOnline(context.Background()); err != nil {
slog.Error("在线统计失败", "err", err)
}
case <-a.onlinePoke:
if debounce == nil {
debounce = time.NewTimer(onlineDebounce)
debounceC = debounce.C
}
case <-debounceC:
debounce = nil
debounceC = nil
if err := a.refreshOnline(context.Background()); err != nil {
slog.Error("在线统计失败", "err", err)
}
@@ -239,23 +310,91 @@ func (a *App) handleRange(w http.ResponseWriter, r *http.Request) {
writeAPIErr(w, aerr)
return
}
fromMin, toMin := start.Unix()/60, end.Unix()/60
a.rangeMu.Lock()
rows, err := a.store.Query(r.Context(), start.Unix()/60, end.Unix()/60)
rows, err := a.store.Query(r.Context(), fromMin, toMin)
daily, dailyErr := a.store.QueryDaily(r.Context(), fromMin, toMin)
a.rangeMu.Unlock()
if err != nil {
slog.Error("时段查询失败", "err", err)
if err != nil || dailyErr != nil {
slog.Error("时段查询失败", "err", err, "daily", dailyErr)
writeAPIErr(w, errStats())
return
}
hits, sessions := a.rec.Snapshot()
rows = mergePending(rows, hits, sessions, fromMin, toMin)
daily = mergeDailyPending(daily, hits, sessions, fromMin, toMin)
tables := sortedTables(estimate(rows).Tables)
writeJSON(w, http.StatusOK, rangeResp{
Start: formatRFC3339(start),
End: formatRFC3339(end),
Total: tableSum(tables),
Tables: tables,
Daily: dailySeries(daily, start, end),
})
}
func beijingDay(minute int64) int64 {
return (minute*60 + 8*3600) / 86400
}
func formatBeijingDay(day int64) string {
return time.Unix(day*86400-8*3600, 0).In(cst).Format("2006-01-02")
}
func mergeDailyPending(rows []dayRow, hits []hitKey, sessions map[string]sessionAgg, from, to int64) []dayRow {
index := make(map[[3]string]int, len(rows))
for i, row := range rows {
index[[3]string{strconv.FormatInt(row.day, 10), row.table, row.sid}] = i
}
for _, hit := range hits {
if hit.minute < from || hit.minute > to {
continue
}
sess, ok := sessions[hit.sid]
if !ok {
continue
}
day := beijingDay(hit.minute)
key := [3]string{strconv.FormatInt(day, 10), hit.table, hit.sid}
if i, ok := index[key]; ok {
if hit.minute < rows[i].first {
rows[i].first = hit.minute
}
if hit.minute > rows[i].last {
rows[i].last = hit.minute
}
continue
}
rows = append(rows, dayRow{
day: day,
sessionRow: sessionRow{
table: hit.table,
sid: hit.sid,
fp: sess.fp,
first: hit.minute,
last: hit.minute,
},
})
index[key] = len(rows) - 1
}
return rows
}
func dailySeries(rows []dayRow, start, end time.Time) []dayCount {
byDay := map[int64][]sessionRow{}
for _, row := range rows {
byDay[row.day] = append(byDay[row.day], row.sessionRow)
}
first := beijingDay(start.Unix() / 60)
last := beijingDay(end.Unix() / 60)
out := make([]dayCount, 0, last-first+1)
for day := first; day <= last; day++ {
tables := sortedTables(estimate(byDay[day]).Tables)
out = append(out, dayCount{Date: formatBeijingDay(day), Count: tableSum(tables)})
}
return out
}
func (a *App) handleHealth(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))