272 lines
6.4 KiB
Go
272 lines
6.4 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"`
|
|
}
|
|
|
|
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: "时段不能超过 72 小时"}
|
|
}
|
|
|
|
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) 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
|
|
}
|
|
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)
|
|
}
|
|
t := time.NewTicker(onlineRefreshEvery)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
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
|
|
}
|
|
a.rangeMu.Lock()
|
|
rows, err := a.store.Query(r.Context(), start.Unix()/60, end.Unix()/60)
|
|
a.rangeMu.Unlock()
|
|
if err != nil {
|
|
slog.Error("时段查询失败", "err", err)
|
|
writeAPIErr(w, errStats())
|
|
return
|
|
}
|
|
tables := sortedTables(estimate(rows).Tables)
|
|
writeJSON(w, http.StatusOK, rangeResp{
|
|
Start: formatRFC3339(start),
|
|
End: formatRFC3339(end),
|
|
Total: tableSum(tables),
|
|
Tables: tables,
|
|
})
|
|
}
|
|
|
|
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)
|
|
}
|