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

411 lines
9.9 KiB
Go

package main
import (
"context"
_ "embed"
"encoding/json"
"log/slog"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
//go:embed web/index.html
var indexHTML []byte
var cst = time.FixedZone("CST", 8*3600)
const timeRFC3339 = time.RFC3339
type tableCount struct {
Table string `json:"table"`
Count int `json:"count"`
}
type onlineResp struct {
ServerTime string `json:"server_time"`
OnlineMinutes int `json:"online_minutes"`
Total int `json:"total"`
Tables []tableCount `json:"tables"`
}
type rangeResp struct {
Start string `json:"start"`
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 {
status int
Code string `json:"error"`
Message string `json:"message"`
Earliest string `json:"earliest,omitempty"`
}
func errBadTime() *apiErr {
return &apiErr{status: http.StatusBadRequest, Code: "bad_time", Message: "时间格式不正确"}
}
func errBadOrder() *apiErr {
return &apiErr{status: http.StatusBadRequest, Code: "bad_order", Message: "起点必须早于终点,且不能晚于当前时间"}
}
func errTooLong() *apiErr {
return &apiErr{status: http.StatusBadRequest, Code: "range_too_long", Message: "时段不能超过 1 年"}
}
func errTooOld(earliest time.Time) *apiErr {
return &apiErr{
status: http.StatusBadRequest,
Code: "range_too_old",
Message: "最早只能查到 " + formatChinese(earliest),
Earliest: formatRFC3339(earliest),
}
}
func errStats() *apiErr {
return &apiErr{status: http.StatusServiceUnavailable, Code: "stats_unavailable", Message: "统计暂时不可用"}
}
func formatRFC3339(t time.Time) string {
return t.In(cst).Format(timeRFC3339)
}
func formatChinese(t time.Time) string {
return t.In(cst).Format("2006年/01月/02日 15时04分05秒")
}
func parseFlexTime(v string) (time.Time, error) {
t, err := time.Parse(time.RFC3339, v)
if err != nil && strings.Contains(v, " ") {
t, err = time.Parse(time.RFC3339, strings.ReplaceAll(v, " ", "+"))
}
return t, err
}
func parseRange(startRaw, endRaw string, now time.Time) (time.Time, time.Time, *apiErr) {
start, err := parseFlexTime(startRaw)
if err != nil {
return time.Time{}, time.Time{}, errBadTime()
}
end, err := parseFlexTime(endRaw)
if err != nil {
return time.Time{}, time.Time{}, errBadTime()
}
if !start.Before(end) {
return time.Time{}, time.Time{}, errBadOrder()
}
if end.Sub(start) > retainDuration {
return time.Time{}, time.Time{}, errTooLong()
}
if end.After(now) {
end = now
}
earliest := now.Add(-retainDuration)
if start.Before(earliest) {
if earliest.Sub(start) <= rangeSlack {
start = earliest
} else {
return time.Time{}, time.Time{}, errTooOld(earliest)
}
}
if !start.Before(end) {
return time.Time{}, time.Time{}, errBadOrder()
}
return start, end, nil
}
func sortedTables(m map[string]int) []tableCount {
out := make([]tableCount, 0, len(m))
for name, n := range m {
if n <= 0 {
continue
}
out = append(out, tableCount{Table: name, Count: n})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Count != out[j].Count {
return out[i].Count > out[j].Count
}
return out[i].Table < out[j].Table
})
return out
}
func writeJSONBytes(w http.ResponseWriter, code int, body []byte) {
h := w.Header()
h.Set("Content-Type", "application/json; charset=utf-8")
h.Set("Cache-Control", "no-store")
h.Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(code)
_, _ = w.Write(body)
}
func writeJSON(w http.ResponseWriter, code int, v any) {
body, err := json.Marshal(v)
if err != nil {
slog.Error("编码 JSON 失败", "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
writeJSONBytes(w, code, body)
}
func writeAPIErr(w http.ResponseWriter, e *apiErr) {
writeJSON(w, e.status, e)
}
func tableSum(tables []tableCount) int {
n := 0
for _, t := range tables {
n += t.Count
}
return n
}
func (a *App) cachedOnline() []byte {
a.onlineMu.Lock()
defer a.onlineMu.Unlock()
return a.onlineJSON
}
func (a *App) refreshOnline(ctx context.Context) error {
now := a.now()
body, err := a.buildOnline(ctx, now)
if err != nil {
return err
}
a.onlineMu.Lock()
a.onlineAt = now
a.onlineJSON = body
a.onlineMu.Unlock()
return nil
}
func (a *App) handleOnline(w http.ResponseWriter, r *http.Request) {
body := a.cachedOnline()
if body == nil {
if err := a.refreshOnline(context.Background()); err != nil {
slog.Error("在线统计失败", "err", err)
writeAPIErr(w, errStats())
return
}
body = a.cachedOnline()
}
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)
rows, err := a.store.Query(ctx, from, m)
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),
OnlineMinutes: a.cfg.OnlineMinutes,
Total: tableSum(tables),
Tables: tables,
})
}
func (a *App) loopOnline(ctx context.Context) {
if err := a.refreshOnline(context.Background()); err != nil {
slog.Error("在线统计失败", "err", err)
}
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 <-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)
}
}
}
}
func (a *App) handleRange(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
start, end, aerr := parseRange(q.Get("start"), q.Get("end"), a.now())
if aerr != nil {
writeAPIErr(w, aerr)
return
}
fromMin, toMin := start.Unix()/60, end.Unix()/60
a.rangeMu.Lock()
rows, err := a.store.Query(r.Context(), fromMin, toMin)
daily, dailyErr := a.store.QueryDaily(r.Context(), fromMin, toMin)
a.rangeMu.Unlock()
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"))
}
func (a *App) handleIndex(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Type", "text/html; charset=utf-8")
h.Set("Cache-Control", "no-cache")
h.Set("Content-Length", strconv.Itoa(len(indexHTML)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(indexHTML)
}