feat: 新增 XYZ 图层使用人数统计服务
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
|
deploy/*.py text eol=lf
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# 运行数据与 SQLite 文件
|
||||||
|
/data/
|
||||||
|
|
||||||
|
# 编译产物
|
||||||
|
/xyzserver
|
||||||
|
/xyzserver.exe
|
||||||
|
*.exe
|
||||||
|
*.test
|
||||||
|
*.out
|
||||||
|
/deploy/.build/
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# XYZ 图层使用人数统计
|
||||||
|
|
||||||
|
公开的 XYZ 地址。QGIS / QField 请求瓦片时返回一张透明 PNG,并按地址里的 `table` 估算使用人数。统计页不用登录。
|
||||||
|
|
||||||
|
## 编译
|
||||||
|
|
||||||
|
需要 Go 1.25 及以上。在 `xyzserver` 目录执行。依赖只有 `modernc.org/sqlite`(纯 Go,不需要 CGO)。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:GOPROXY = "https://goproxy.cn,direct"
|
||||||
|
$env:CGO_ENABLED = "0"
|
||||||
|
go build -trimpath -ldflags "-s -w" -o xyzserver.exe .
|
||||||
|
```
|
||||||
|
|
||||||
|
交叉编译 Linux:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:GOPROXY = "https://goproxy.cn,direct"
|
||||||
|
$env:CGO_ENABLED = "0"
|
||||||
|
$env:GOOS = "linux"
|
||||||
|
$env:GOARCH = "amd64"
|
||||||
|
go build -trimpath -ldflags "-s -w" -o xyzserver .
|
||||||
|
```
|
||||||
|
|
||||||
|
## 环境变量
|
||||||
|
|
||||||
|
| 变量 | 默认值 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `XYZ_LISTEN` | `127.0.0.1:8080` | 监听地址。前面有反向代理时只监听本机 |
|
||||||
|
| `XYZ_DATA_DIR` | `./data` | 数据目录,数据库文件为 `xyz.db` |
|
||||||
|
| `XYZ_ONLINE_MINUTES` | `15` | 在线窗口(分钟),允许 1 到 120 |
|
||||||
|
| `XYZ_TRUST_PROXY` | `false` | 为 `true` 时从 `X-Real-IP` 取客户端 IP,并从 `X-Forwarded-Proto` 判断是否 HTTPS |
|
||||||
|
| `XYZ_COUNT_HTTPS_ONLY` | `false` | 为 `true` 时只统计走 HTTPS 的请求。线上部署脚本会打开 |
|
||||||
|
| `XYZ_TLS_CERT`、`XYZ_TLS_KEY` | 空 | 两个都设置时由程序直接提供 HTTPS |
|
||||||
|
| `XYZ_DEBUG_LOG` | `0` | 为 `1` 时逐条打印瓦片请求,只用于客户端实测 |
|
||||||
|
|
||||||
|
配置不合法时进程直接退出。数据保留 72 小时、写库间隔 10 秒、每分钟新增上限 20000 等是固定值,不能通过环境变量修改。
|
||||||
|
|
||||||
|
线上只把 **QGIS / QField** 经 **HTTPS** 发来的瓦片计入。页面上的「总在线连接」是各图层在线人数之和(同一台设备用两个图层算 2)。Go 每 30 秒算一次放在内存里,打开多少个统计页都不会多查数据库。不使用 Redis。
|
||||||
|
|
||||||
|
## 运行
|
||||||
|
|
||||||
|
程序会自行创建数据目录。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:XYZ_LISTEN = "127.0.0.1:8080"
|
||||||
|
$env:XYZ_DATA_DIR = ".\data"
|
||||||
|
.\xyzserver.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
- 统计页:<http://127.0.0.1:8080/>
|
||||||
|
- 图层地址(QGIS / QField 里 `{z}/{x}/{y}` 保持原样):`http://127.0.0.1:8080/tiles/grid/{z}/{x}/{y}.png`
|
||||||
|
- 直接打开一张瓦片:<http://127.0.0.1:8080/tiles/grid/0/0/0.png>
|
||||||
|
- 存活检查:<http://127.0.0.1:8080/healthz>
|
||||||
|
|
||||||
|
`Ctrl+C` 后最多等待 10 秒结束正在处理的请求,再把内存里的记录写入数据库并关闭文件。
|
||||||
|
|
||||||
|
## 部署要点
|
||||||
|
|
||||||
|
- 用 `CGO_ENABLED=0` 编译出的单个可执行文件即可,不依赖 C 运行库。
|
||||||
|
- HTTPS 用现有的 Caddy 或 Nginx 反代到 `127.0.0.1:8080`,或设置 `XYZ_TLS_CERT` / `XYZ_TLS_KEY` 由程序自己监听。
|
||||||
|
- 有反向代理时:Go 只监听 `127.0.0.1`,`XYZ_TRUST_PROXY=true`,并由代理设置 `X-Real-IP`。端口不要直接暴露到公网,否则客户端 IP 可以被伪造。
|
||||||
|
- 不要在前面加 CDN,也不要缓存 `/tiles/`。瓦片响应是 `Cache-Control: no-store`。
|
||||||
|
- Nginx 反代需要同时打开 keepalive、`proxy_http_version 1.1`,并清空 `Connection`,避免每个瓦片都新建一条到 Go 的连接。
|
||||||
|
|
||||||
|
## 一键部署到 xyz.asio.asia
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell -ExecutionPolicy Bypass -File deploy\deploy.ps1 # 正常部署
|
||||||
|
powershell -ExecutionPolicy Bypass -File deploy\deploy.ps1 -DebugLog # 打开逐条瓦片日志(客户端实测用)
|
||||||
|
powershell -ExecutionPolicy Bypass -File deploy\deploy.ps1 -SetupKey # 新电脑首次使用:生成密钥,输入一次服务器密码
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本依次执行:本地测试、编译 Linux 版、上传、服务器上安装并重启、外网检查,可以重复执行。登录使用 `~\.ssh\xyzserver_deploy` 密钥,脚本里不保存密码。
|
||||||
|
|
||||||
|
服务器上的布局:
|
||||||
|
|
||||||
|
| 项 | 位置 |
|
||||||
|
| --- | --- |
|
||||||
|
| 程序 | `/opt/xyzserver/xyzserver`(上一版本 `xyzserver.prev`,新版本启动失败会自动回滚) |
|
||||||
|
| 数据 | `/opt/xyzserver/data/xyz.db` |
|
||||||
|
| 服务 | `systemctl status xyzserver`,日志 `journalctl -u xyzserver -f` |
|
||||||
|
| 端口 | `127.0.0.1:18480`,不对外开放 |
|
||||||
|
| 宝塔网站 | `xyz.asio.asia`,SSL 在宝塔里申请即可 |
|
||||||
|
| 转发规则 | 宝塔「伪静态」`/www/server/panel/vhost/rewrite/xyz.asio.asia.conf`,以及 `/www/server/panel/vhost/nginx/0.xyzserver.upstream.conf` |
|
||||||
|
|
||||||
|
不要在宝塔里给这个网站添加「反向代理」,也不要改它的「伪静态」:宝塔的反向代理会给 `.png` 加 `expires`,覆盖瓦片的 `no-store`,统计会失真。转发规则每次部署都会重写。
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:GOPROXY = "https://goproxy.cn,direct"
|
||||||
|
$env:CGO_ENABLED = "0"
|
||||||
|
go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
真实客户端是否回传 cookie,需要按 `docs/DEV.md` 第 2 节在 QGIS 3.22+ 与 QField 上补测。本环境没有这些客户端,交付时未做该项实测。
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseRange(t *testing.T) {
|
||||||
|
now := time.Date(2026, 9, 23, 11, 30, 0, 0, cst)
|
||||||
|
earliest := now.Add(-retainDuration)
|
||||||
|
|
||||||
|
t.Run("bad time", func(t *testing.T) {
|
||||||
|
_, _, err := parseRange("nope", now.Format(time.RFC3339), now)
|
||||||
|
if err == nil || err.Code != "bad_time" || err.Message != "时间格式不正确" {
|
||||||
|
t.Fatalf("%+v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("bad order", func(t *testing.T) {
|
||||||
|
_, _, err := parseRange(now.Format(time.RFC3339), now.Add(-time.Hour).Format(time.RFC3339), now)
|
||||||
|
if err == nil || err.Code != "bad_order" {
|
||||||
|
t.Fatalf("%+v", err)
|
||||||
|
}
|
||||||
|
_, _, err = parseRange(now.Add(-time.Hour).Format(time.RFC3339), now.Add(-time.Hour).Format(time.RFC3339), now)
|
||||||
|
if err == nil || err.Code != "bad_order" || err.Message != "起点必须早于终点,且不能晚于当前时间" {
|
||||||
|
t.Fatalf("%+v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("future start", func(t *testing.T) {
|
||||||
|
_, _, err := parseRange(now.Add(time.Hour).Format(time.RFC3339), now.Add(2*time.Hour).Format(time.RFC3339), now)
|
||||||
|
if err == nil || err.Code != "bad_order" {
|
||||||
|
t.Fatalf("%+v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("too long", func(t *testing.T) {
|
||||||
|
_, _, err := parseRange(now.Add(-73*time.Hour).Format(time.RFC3339), now.Format(time.RFC3339), now)
|
||||||
|
if err == nil || err.Code != "range_too_long" || err.Message != "时段不能超过 72 小时" {
|
||||||
|
t.Fatalf("%+v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("exactly 72h", func(t *testing.T) {
|
||||||
|
_, _, err := parseRange(earliest.Format(time.RFC3339), now.Format(time.RFC3339), now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("truncate future end", func(t *testing.T) {
|
||||||
|
_, end, err := parseRange(now.Add(-time.Hour).Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339), now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !end.Equal(now) {
|
||||||
|
t.Fatalf("end %s", end)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("start 3 min early", func(t *testing.T) {
|
||||||
|
start, end, err := parseRange(earliest.Add(-3*time.Minute).Format(time.RFC3339), now.Add(-3*time.Minute).Format(time.RFC3339), now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !start.Equal(earliest) {
|
||||||
|
t.Fatalf("start %s want %s", start, earliest)
|
||||||
|
}
|
||||||
|
if !end.Equal(now.Add(-3 * time.Minute)) {
|
||||||
|
t.Fatalf("end %s", end)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("start 10 min early", func(t *testing.T) {
|
||||||
|
_, _, err := parseRange(earliest.Add(-10*time.Minute).Format(time.RFC3339), now.Add(-10*time.Minute).Format(time.RFC3339), now)
|
||||||
|
if err == nil || err.Code != "range_too_old" {
|
||||||
|
t.Fatalf("%+v", err)
|
||||||
|
}
|
||||||
|
if err.Earliest != formatRFC3339(earliest) {
|
||||||
|
t.Fatalf("earliest %s", err.Earliest)
|
||||||
|
}
|
||||||
|
want := "最早只能查到 " + formatChinese(earliest)
|
||||||
|
if err.Message != want {
|
||||||
|
t.Fatalf("message %q", err.Message)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
t.Run("space becomes plus", func(t *testing.T) {
|
||||||
|
start, end, err := parseRange("2026-09-23T10:00:00 08:00", "2026-09-23T11:00:00 08:00", now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if start.Hour() != 10 || end.Hour() != 11 {
|
||||||
|
t.Fatalf("start %s end %s", start, end)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRangeHTTP(t *testing.T) {
|
||||||
|
now := time.Date(2026, 9, 23, 11, 30, 0, 0, cst)
|
||||||
|
app := newTestApp(t, func() time.Time { return now })
|
||||||
|
earliest := now.Add(-retainDuration)
|
||||||
|
|
||||||
|
call := func(raw string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/range?"+raw, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
app.Handler().ServeHTTP(rr, req)
|
||||||
|
return rr
|
||||||
|
}
|
||||||
|
decodeErr := func(rr *httptest.ResponseRecorder) errJSON {
|
||||||
|
t.Helper()
|
||||||
|
var body errJSON
|
||||||
|
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
|
||||||
|
rr := call("start=foo&end=bar")
|
||||||
|
if rr.Code != 400 || decodeErr(rr).Error != "bad_time" {
|
||||||
|
t.Fatalf("%d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
if ct := rr.Header().Get("Content-Type"); !strings.Contains(ct, "application/json") {
|
||||||
|
t.Fatalf("content-type %s", ct)
|
||||||
|
}
|
||||||
|
if rr.Header().Get("Cache-Control") != "no-store" {
|
||||||
|
t.Fatal(rr.Header().Get("Cache-Control"))
|
||||||
|
}
|
||||||
|
|
||||||
|
q := url.Values{}
|
||||||
|
q.Set("start", now.Add(-73*time.Hour).Format(time.RFC3339))
|
||||||
|
q.Set("end", now.Format(time.RFC3339))
|
||||||
|
rr = call(q.Encode())
|
||||||
|
if rr.Code != 400 || decodeErr(rr).Error != "range_too_long" {
|
||||||
|
t.Fatalf("%d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
q = url.Values{}
|
||||||
|
q.Set("start", earliest.Add(-10*time.Minute).Format(time.RFC3339))
|
||||||
|
q.Set("end", now.Add(-10*time.Minute).Format(time.RFC3339))
|
||||||
|
rr = call(q.Encode())
|
||||||
|
body := decodeErr(rr)
|
||||||
|
if rr.Code != 400 || body.Error != "range_too_old" || body.Earliest != formatRFC3339(earliest) {
|
||||||
|
t.Fatalf("%d %+v", rr.Code, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
q = url.Values{}
|
||||||
|
q.Set("start", earliest.Add(-3*time.Minute).Format(time.RFC3339))
|
||||||
|
q.Set("end", now.Add(-3*time.Minute).Format(time.RFC3339))
|
||||||
|
rr = call(q.Encode())
|
||||||
|
if rr.Code != 200 {
|
||||||
|
t.Fatalf("%d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
var ok rangeResp
|
||||||
|
if err := json.Unmarshal(rr.Body.Bytes(), &ok); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ok.Start != formatRFC3339(earliest) {
|
||||||
|
t.Fatalf("adjusted start %s", ok.Start)
|
||||||
|
}
|
||||||
|
|
||||||
|
rr = call("start=2026-09-23T10:00:00+08:00&end=2026-09-23T11:00:00+08:00")
|
||||||
|
if rr.Code != 200 {
|
||||||
|
t.Fatalf("plus in query: %d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOnlineSurvivesCanceledRequest(t *testing.T) {
|
||||||
|
app := newTestApp(t, func() time.Time { return time.Date(2026, 9, 23, 12, 0, 0, 0, cst) })
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/api/online", nil).WithContext(ctx)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
app.Handler().ServeHTTP(rr, req)
|
||||||
|
if rr.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status %d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type errJSON struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
Message string `json:"message"`
|
||||||
|
Earliest string `json:"earliest"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
retainDuration = 72 * time.Hour
|
||||||
|
flushEvery = 10 * time.Second
|
||||||
|
onlineRefreshEvery = 30 * time.Second
|
||||||
|
cleanupEvery = time.Hour
|
||||||
|
summaryEvery = 10 * time.Minute
|
||||||
|
rangeSlack = 5 * time.Minute
|
||||||
|
shutdownFor = 10 * time.Second
|
||||||
|
cookieMaxAge = 31536000
|
||||||
|
uaMaxBytes = 256
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config 来自环境变量。非法值直接失败,不回退到默认值。
|
||||||
|
type Config struct {
|
||||||
|
Listen string
|
||||||
|
DataDir string
|
||||||
|
OnlineMinutes int
|
||||||
|
TrustProxy bool
|
||||||
|
HTTPSOnly bool
|
||||||
|
TLSCert string
|
||||||
|
TLSKey string
|
||||||
|
DebugLog bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadConfig() (Config, error) {
|
||||||
|
cfg := Config{
|
||||||
|
Listen: "127.0.0.1:8080",
|
||||||
|
DataDir: "./data",
|
||||||
|
OnlineMinutes: 15,
|
||||||
|
}
|
||||||
|
|
||||||
|
if v, ok := os.LookupEnv("XYZ_LISTEN"); ok {
|
||||||
|
if _, _, err := net.SplitHostPort(v); err != nil {
|
||||||
|
return Config{}, fmt.Errorf("XYZ_LISTEN 无效: %q", v)
|
||||||
|
}
|
||||||
|
cfg.Listen = v
|
||||||
|
}
|
||||||
|
if v, ok := os.LookupEnv("XYZ_DATA_DIR"); ok {
|
||||||
|
if v == "" {
|
||||||
|
return Config{}, fmt.Errorf("XYZ_DATA_DIR 不能为空")
|
||||||
|
}
|
||||||
|
cfg.DataDir = v
|
||||||
|
}
|
||||||
|
if v, ok := os.LookupEnv("XYZ_ONLINE_MINUTES"); ok {
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil || n < 1 || n > 120 {
|
||||||
|
return Config{}, fmt.Errorf("XYZ_ONLINE_MINUTES 必须是 1 到 120 的整数")
|
||||||
|
}
|
||||||
|
cfg.OnlineMinutes = n
|
||||||
|
}
|
||||||
|
if v, ok := os.LookupEnv("XYZ_TRUST_PROXY"); ok {
|
||||||
|
switch v {
|
||||||
|
case "true":
|
||||||
|
cfg.TrustProxy = true
|
||||||
|
case "false":
|
||||||
|
cfg.TrustProxy = false
|
||||||
|
default:
|
||||||
|
return Config{}, fmt.Errorf("XYZ_TRUST_PROXY 必须是 true 或 false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v, ok := os.LookupEnv("XYZ_COUNT_HTTPS_ONLY"); ok {
|
||||||
|
switch v {
|
||||||
|
case "true":
|
||||||
|
cfg.HTTPSOnly = true
|
||||||
|
case "false":
|
||||||
|
cfg.HTTPSOnly = false
|
||||||
|
default:
|
||||||
|
return Config{}, fmt.Errorf("XYZ_COUNT_HTTPS_ONLY 必须是 true 或 false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cert, hasCert := os.LookupEnv("XYZ_TLS_CERT")
|
||||||
|
key, hasKey := os.LookupEnv("XYZ_TLS_KEY")
|
||||||
|
if hasCert || hasKey {
|
||||||
|
if cert == "" || key == "" {
|
||||||
|
return Config{}, fmt.Errorf("XYZ_TLS_CERT 和 XYZ_TLS_KEY 必须同时设置")
|
||||||
|
}
|
||||||
|
cfg.TLSCert = cert
|
||||||
|
cfg.TLSKey = key
|
||||||
|
}
|
||||||
|
if v, ok := os.LookupEnv("XYZ_DEBUG_LOG"); ok {
|
||||||
|
switch v {
|
||||||
|
case "1":
|
||||||
|
cfg.DebugLog = true
|
||||||
|
case "0":
|
||||||
|
cfg.DebugLog = false
|
||||||
|
default:
|
||||||
|
return Config{}, fmt.Errorf("XYZ_DEBUG_LOG 必须是 0 或 1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func clearXYZEnv(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
keys := []string{
|
||||||
|
"XYZ_LISTEN", "XYZ_DATA_DIR", "XYZ_ONLINE_MINUTES",
|
||||||
|
"XYZ_TRUST_PROXY", "XYZ_COUNT_HTTPS_ONLY", "XYZ_TLS_CERT", "XYZ_TLS_KEY", "XYZ_DEBUG_LOG",
|
||||||
|
}
|
||||||
|
for _, key := range keys {
|
||||||
|
clearOneEnv(t, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clearOneEnv(t *testing.T, key string) {
|
||||||
|
t.Helper()
|
||||||
|
val, ok := os.LookupEnv(key)
|
||||||
|
if err := os.Unsetenv(key); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if ok {
|
||||||
|
_ = os.Setenv(key, val)
|
||||||
|
} else {
|
||||||
|
_ = os.Unsetenv(key)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigDefaults(t *testing.T) {
|
||||||
|
clearXYZEnv(t)
|
||||||
|
cfg, err := loadConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cfg.Listen != "127.0.0.1:8080" || cfg.DataDir != "./data" || cfg.OnlineMinutes != 15 || cfg.TrustProxy || cfg.HTTPSOnly || cfg.DebugLog || cfg.TLSCert != "" || cfg.TLSKey != "" {
|
||||||
|
t.Fatalf("%+v", cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigValuesAndRejects(t *testing.T) {
|
||||||
|
clearXYZEnv(t)
|
||||||
|
t.Setenv("XYZ_LISTEN", "127.0.0.1:9090")
|
||||||
|
t.Setenv("XYZ_DATA_DIR", `D:\xyz-data`)
|
||||||
|
t.Setenv("XYZ_ONLINE_MINUTES", "120")
|
||||||
|
t.Setenv("XYZ_TRUST_PROXY", "true")
|
||||||
|
t.Setenv("XYZ_COUNT_HTTPS_ONLY", "true")
|
||||||
|
t.Setenv("XYZ_DEBUG_LOG", "1")
|
||||||
|
t.Setenv("XYZ_TLS_CERT", "cert.pem")
|
||||||
|
t.Setenv("XYZ_TLS_KEY", "key.pem")
|
||||||
|
cfg, err := loadConfig()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cfg.Listen != "127.0.0.1:9090" || cfg.DataDir != `D:\xyz-data` || cfg.OnlineMinutes != 120 || !cfg.TrustProxy || !cfg.HTTPSOnly || !cfg.DebugLog || cfg.TLSCert != "cert.pem" || cfg.TLSKey != "key.pem" {
|
||||||
|
t.Fatalf("%+v", cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
key, val, needle string
|
||||||
|
}{
|
||||||
|
{"XYZ_LISTEN", "bad", "XYZ_LISTEN"},
|
||||||
|
{"XYZ_DATA_DIR", "", "XYZ_DATA_DIR"},
|
||||||
|
{"XYZ_ONLINE_MINUTES", "0", "XYZ_ONLINE_MINUTES"},
|
||||||
|
{"XYZ_ONLINE_MINUTES", "121", "XYZ_ONLINE_MINUTES"},
|
||||||
|
{"XYZ_ONLINE_MINUTES", "abc", "XYZ_ONLINE_MINUTES"},
|
||||||
|
{"XYZ_TRUST_PROXY", "yes", "XYZ_TRUST_PROXY"},
|
||||||
|
{"XYZ_COUNT_HTTPS_ONLY", "1", "XYZ_COUNT_HTTPS_ONLY"},
|
||||||
|
{"XYZ_DEBUG_LOG", "2", "XYZ_DEBUG_LOG"},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.key+"="+tc.val, func(t *testing.T) {
|
||||||
|
clearXYZEnv(t)
|
||||||
|
t.Setenv("XYZ_LISTEN", "127.0.0.1:8080")
|
||||||
|
t.Setenv("XYZ_DATA_DIR", "data")
|
||||||
|
t.Setenv("XYZ_ONLINE_MINUTES", "15")
|
||||||
|
t.Setenv("XYZ_TRUST_PROXY", "false")
|
||||||
|
t.Setenv("XYZ_COUNT_HTTPS_ONLY", "false")
|
||||||
|
t.Setenv("XYZ_DEBUG_LOG", "0")
|
||||||
|
t.Setenv(tc.key, tc.val)
|
||||||
|
_, err := loadConfig()
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tc.needle) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("tls half", func(t *testing.T) {
|
||||||
|
clearXYZEnv(t)
|
||||||
|
t.Setenv("XYZ_TLS_CERT", "cert.pem")
|
||||||
|
_, err := loadConfig()
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "XYZ_TLS") {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# 用宝塔自己的接口新建网站,使其出现在面板的网站列表里。
|
||||||
|
# 用法:/www/server/panel/pyenv/bin/python3 bt_addsite.py <域名> <网站根目录>
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
os.chdir("/www/server/panel")
|
||||||
|
sys.path.insert(0, "/www/server/panel/class")
|
||||||
|
|
||||||
|
import public # noqa: E402
|
||||||
|
import panelSite # noqa: E402
|
||||||
|
|
||||||
|
domain, root = sys.argv[1], sys.argv[2]
|
||||||
|
|
||||||
|
get = public.dict_obj()
|
||||||
|
get.webname = json.dumps({"domain": domain, "domainlist": [], "count": 0})
|
||||||
|
get.path = root
|
||||||
|
get.type_id = "0"
|
||||||
|
get.type = "PHP"
|
||||||
|
get.version = "00"
|
||||||
|
get.port = "80"
|
||||||
|
get.ps = "XYZ 图层使用人数统计(xyzserver)"
|
||||||
|
get.ftp = "false"
|
||||||
|
get.sql = "false"
|
||||||
|
get.codeing = "utf8mb4"
|
||||||
|
|
||||||
|
res = panelSite.panelSite().AddSite(get)
|
||||||
|
print(json.dumps(res, ensure_ascii=False, default=str))
|
||||||
|
ok = isinstance(res, dict) and (res.get("siteStatus") is True or res.get("status") is True)
|
||||||
|
sys.exit(0 if ok else 1)
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
<#
|
||||||
|
一键部署 xyzserver:本地测试 → 编译 Linux 版 → 上传 → 服务器上安装并重启 → 外网检查。
|
||||||
|
可重复执行,首次会顺带在宝塔里新建网站。
|
||||||
|
|
||||||
|
用法(在 xyzserver 目录或任意目录):
|
||||||
|
powershell -ExecutionPolicy Bypass -File deploy\deploy.ps1
|
||||||
|
powershell -ExecutionPolicy Bypass -File deploy\deploy.ps1 -DebugLog # 打开逐条瓦片日志,用于客户端实测
|
||||||
|
powershell -ExecutionPolicy Bypass -File deploy\deploy.ps1 -SetupKey # 新电脑上首次使用:生成密钥并输入一次服务器密码
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[string]$Server = "asio.asia",
|
||||||
|
[string]$User = "root",
|
||||||
|
[int]$SshPort = 22,
|
||||||
|
[string]$Domain = "xyz.asio.asia",
|
||||||
|
[int]$AppPort = 18480,
|
||||||
|
[string]$KeyFile = "$HOME\.ssh\xyzserver_deploy",
|
||||||
|
[switch]$DebugLog,
|
||||||
|
[switch]$SkipTests,
|
||||||
|
[switch]$SetupKey
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
$ProjectDir = Split-Path -Parent $PSScriptRoot
|
||||||
|
$Target = "$User@$Server"
|
||||||
|
$SshArgs = @("-i", $KeyFile, "-p", "$SshPort", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=15")
|
||||||
|
$ScpArgs = @("-i", $KeyFile, "-P", "$SshPort", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=15")
|
||||||
|
|
||||||
|
function Step($msg) { Write-Host "==> $msg" -ForegroundColor Cyan }
|
||||||
|
|
||||||
|
function Invoke-Checked {
|
||||||
|
param([string]$Exe, [string[]]$Arguments)
|
||||||
|
& $Exe @Arguments
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "$Exe 执行失败(退出码 $LASTEXITCODE)" }
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($SetupKey) {
|
||||||
|
Step "配置 SSH 密钥登录"
|
||||||
|
if (-not (Test-Path $KeyFile)) {
|
||||||
|
New-Item -ItemType Directory -Force (Split-Path $KeyFile) | Out-Null
|
||||||
|
& ssh-keygen -q -t ed25519 -f $KeyFile -N '""' -C "xyzserver-deploy@$env:COMPUTERNAME"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "生成密钥失败" }
|
||||||
|
}
|
||||||
|
$pub = (Get-Content "$KeyFile.pub" -Raw).Trim()
|
||||||
|
Write-Host "接下来会提示输入一次 $Target 的密码。"
|
||||||
|
& ssh -p $SshPort -o StrictHostKeyChecking=accept-new $Target "umask 077; mkdir -p ~/.ssh; touch ~/.ssh/authorized_keys; grep -qxF '$pub' ~/.ssh/authorized_keys || echo '$pub' >> ~/.ssh/authorized_keys"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "安装公钥失败" }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Path $KeyFile)) {
|
||||||
|
throw "没有找到部署密钥 $KeyFile。请先加 -SetupKey 运行一次。"
|
||||||
|
}
|
||||||
|
& ssh @SshArgs $Target "true"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "无法用密钥登录 $Target。请加 -SetupKey 重新配置。" }
|
||||||
|
|
||||||
|
Push-Location $ProjectDir
|
||||||
|
$saved = @{ GOOS = $env:GOOS; GOARCH = $env:GOARCH; CGO_ENABLED = $env:CGO_ENABLED; GOPROXY = $env:GOPROXY }
|
||||||
|
try {
|
||||||
|
if (-not $env:GOPROXY) { $env:GOPROXY = "https://goproxy.cn,direct" }
|
||||||
|
$env:CGO_ENABLED = "0"
|
||||||
|
|
||||||
|
if (-not $SkipTests) {
|
||||||
|
Step "本地测试"
|
||||||
|
Remove-Item Env:GOOS, Env:GOARCH -ErrorAction SilentlyContinue
|
||||||
|
Invoke-Checked go @("test", "./...")
|
||||||
|
}
|
||||||
|
|
||||||
|
Step "编译 Linux 版本"
|
||||||
|
$arch = (& ssh @SshArgs $Target "uname -m").Trim()
|
||||||
|
$goarch = switch ($arch) { "x86_64" { "amd64" } "aarch64" { "arm64" } default { throw "不支持的服务器架构:$arch" } }
|
||||||
|
$buildDir = Join-Path $PSScriptRoot ".build"
|
||||||
|
New-Item -ItemType Directory -Force $buildDir | Out-Null
|
||||||
|
$env:GOOS = "linux"; $env:GOARCH = $goarch
|
||||||
|
Invoke-Checked go @("build", "-trimpath", "-ldflags", "-s -w", "-o", (Join-Path $buildDir "xyzserver"), ".")
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
foreach ($k in $saved.Keys) {
|
||||||
|
if ($null -eq $saved[$k]) { Remove-Item "Env:$k" -ErrorAction SilentlyContinue } else { Set-Item "Env:$k" $saved[$k] }
|
||||||
|
}
|
||||||
|
Pop-Location
|
||||||
|
}
|
||||||
|
|
||||||
|
Step "上传到 $Target"
|
||||||
|
Invoke-Checked ssh (@($SshArgs) + @($Target, "rm -rf /tmp/xyzserver-deploy && mkdir -p /tmp/xyzserver-deploy"))
|
||||||
|
Invoke-Checked scp (@($ScpArgs) + @(
|
||||||
|
(Join-Path $buildDir "xyzserver"),
|
||||||
|
(Join-Path $PSScriptRoot "remote.sh"),
|
||||||
|
(Join-Path $PSScriptRoot "bt_addsite.py"),
|
||||||
|
"${Target}:/tmp/xyzserver-deploy/"))
|
||||||
|
|
||||||
|
Step "服务器上安装并重启"
|
||||||
|
$debug = if ($DebugLog) { "1" } else { "0" }
|
||||||
|
$remoteCmd = "sed -i 's/\r$//' /tmp/xyzserver-deploy/remote.sh /tmp/xyzserver-deploy/bt_addsite.py && " +
|
||||||
|
"XYZ_DOMAIN='$Domain' XYZ_PORT='$AppPort' XYZ_DEBUG='$debug' bash /tmp/xyzserver-deploy/remote.sh"
|
||||||
|
Invoke-Checked ssh (@($SshArgs) + @($Target, $remoteCmd))
|
||||||
|
|
||||||
|
Step "外网检查 http://$Domain"
|
||||||
|
$health = ""
|
||||||
|
for ($i = 0; $i -lt 10 -and $health -ne "ok"; $i++) {
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
$health = & curl.exe -s -m 15 "http://$Domain/healthz"
|
||||||
|
}
|
||||||
|
if ($health -ne "ok") { throw "外网 /healthz 返回:$health" }
|
||||||
|
$headers = & curl.exe -s -m 15 -I "http://$Domain/tiles/deploycheck/0/0/0.png"
|
||||||
|
$headers | Select-String -Pattern "^HTTP/|Cache-Control|Content-Type|Content-Length|Set-Cookie" | ForEach-Object { Write-Host " $_" }
|
||||||
|
if (-not ($headers -match "Cache-Control: no-store")) { throw "瓦片响应缺少 Cache-Control: no-store,请检查 Nginx 配置" }
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "部署完成。统计页:http://$Domain/" -ForegroundColor Green
|
||||||
|
Write-Host "图层地址:http://$Domain/tiles/{table}/{z}/{x}/{y}.png"
|
||||||
|
if ($DebugLog) { Write-Host "调试日志已打开,查看:ssh $Target journalctl -u xyzserver -f。测完请不带 -DebugLog 重新部署一次关闭它。" -ForegroundColor Yellow }
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 在服务器上以 root 执行,由 deploy.ps1 上传后调用。可重复执行。
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
DOMAIN="${XYZ_DOMAIN:?缺少 XYZ_DOMAIN}"
|
||||||
|
PORT="${XYZ_PORT:?缺少 XYZ_PORT}"
|
||||||
|
DEBUG="${XYZ_DEBUG:-0}"
|
||||||
|
|
||||||
|
STAGE=/tmp/xyzserver-deploy
|
||||||
|
APP=/opt/xyzserver
|
||||||
|
PANEL=/www/server/panel
|
||||||
|
NGINX=/www/server/nginx/sbin/nginx
|
||||||
|
VHOST=$PANEL/vhost/nginx
|
||||||
|
SITE_CONF=$VHOST/$DOMAIN.conf
|
||||||
|
REWRITE=$PANEL/vhost/rewrite/$DOMAIN.conf
|
||||||
|
UPSTREAM=$VHOST/0.xyzserver.upstream.conf
|
||||||
|
SITE_ROOT=/www/wwwroot/$DOMAIN
|
||||||
|
|
||||||
|
log() { echo "[deploy] $*"; }
|
||||||
|
fail() { echo "[deploy] 失败:$*" >&2; exit 1; }
|
||||||
|
|
||||||
|
[ -x "$NGINX" ] || fail "没有找到宝塔的 Nginx:$NGINX"
|
||||||
|
[ -d "$PANEL" ] || fail "没有找到宝塔面板:$PANEL"
|
||||||
|
[ -f "$STAGE/xyzserver" ] || fail "没有找到上传的程序:$STAGE/xyzserver"
|
||||||
|
|
||||||
|
log "1/5 运行账号和目录"
|
||||||
|
if ! id xyzserver >/dev/null 2>&1; then
|
||||||
|
useradd --system --no-create-home --shell "$(command -v nologin || echo /sbin/nologin)" xyzserver
|
||||||
|
fi
|
||||||
|
mkdir -p "$APP/data"
|
||||||
|
chown xyzserver:xyzserver "$APP/data"
|
||||||
|
chmod 750 "$APP/data"
|
||||||
|
|
||||||
|
log "2/5 安装程序"
|
||||||
|
install -m 755 "$STAGE/xyzserver" "$APP/xyzserver.new"
|
||||||
|
if [ -f "$APP/xyzserver" ]; then
|
||||||
|
cp -f "$APP/xyzserver" "$APP/xyzserver.prev"
|
||||||
|
fi
|
||||||
|
mv -f "$APP/xyzserver.new" "$APP/xyzserver"
|
||||||
|
|
||||||
|
log "3/5 systemd 服务(端口 127.0.0.1:$PORT,调试日志=$DEBUG)"
|
||||||
|
cat > /etc/systemd/system/xyzserver.service <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=XYZ layer usage counter (xyzserver)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=xyzserver
|
||||||
|
Group=xyzserver
|
||||||
|
ExecStart=$APP/xyzserver
|
||||||
|
Environment=XYZ_LISTEN=127.0.0.1:$PORT
|
||||||
|
Environment=XYZ_DATA_DIR=$APP/data
|
||||||
|
Environment=XYZ_TRUST_PROXY=true
|
||||||
|
Environment=XYZ_COUNT_HTTPS_ONLY=true
|
||||||
|
Environment=XYZ_DEBUG_LOG=$DEBUG
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
LimitNOFILE=65535
|
||||||
|
NoNewPrivileges=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable xyzserver >/dev/null 2>&1
|
||||||
|
systemctl restart xyzserver
|
||||||
|
|
||||||
|
healthy() {
|
||||||
|
for _ in $(seq 1 20); do
|
||||||
|
if curl -fsS "http://127.0.0.1:$PORT/healthz" >/dev/null 2>&1; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 0.5
|
||||||
|
done
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if ! healthy; then
|
||||||
|
journalctl -u xyzserver -n 40 --no-pager || true
|
||||||
|
if [ -f "$APP/xyzserver.prev" ]; then
|
||||||
|
log "新版本启动失败,回滚到上一版本"
|
||||||
|
cp -f "$APP/xyzserver.prev" "$APP/xyzserver"
|
||||||
|
systemctl restart xyzserver
|
||||||
|
healthy && log "已回滚,旧版本正常运行"
|
||||||
|
fi
|
||||||
|
fail "服务没有通过健康检查"
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "4/5 宝塔网站 $DOMAIN"
|
||||||
|
if [ ! -f "$SITE_CONF" ]; then
|
||||||
|
(cd "$PANEL" && "$PANEL/pyenv/bin/python3" "$STAGE/bt_addsite.py" "$DOMAIN" "$SITE_ROOT") \
|
||||||
|
|| fail "宝塔建站失败"
|
||||||
|
fi
|
||||||
|
[ -f "$SITE_CONF" ] || fail "宝塔建站后没有生成 $SITE_CONF"
|
||||||
|
grep -q "include $REWRITE;" "$SITE_CONF" || fail "$SITE_CONF 中没有引用 $REWRITE,请检查网站配置"
|
||||||
|
|
||||||
|
log "5/5 Nginx 转发规则"
|
||||||
|
TS=$(date +%Y%m%d%H%M%S)
|
||||||
|
[ -f "$REWRITE" ] && cp -f "$REWRITE" "$REWRITE.bak.$TS"
|
||||||
|
[ -f "$UPSTREAM" ] && cp -f "$UPSTREAM" "$UPSTREAM.bak.$TS"
|
||||||
|
|
||||||
|
cat > "$UPSTREAM" <<EOF
|
||||||
|
# xyzserver 部署脚本生成,请勿手工修改
|
||||||
|
upstream xyzserver_backend {
|
||||||
|
server 127.0.0.1:$PORT;
|
||||||
|
keepalive 32;
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat > "$REWRITE" <<EOF
|
||||||
|
# xyzserver 部署脚本生成:把整个网站转发给 xyzserver。
|
||||||
|
# 不要在宝塔「伪静态」里改这里,也不要再给本站添加「反向代理」:
|
||||||
|
# 宝塔的反向代理会给 .png 加 expires,覆盖瓦片的 no-store,统计会失真。
|
||||||
|
location ^~ /.well-known/ {
|
||||||
|
root $SITE_ROOT;
|
||||||
|
default_type text/plain;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /tiles/ {
|
||||||
|
proxy_pass http://xyzserver_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
proxy_cache off;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ / {
|
||||||
|
proxy_pass http://xyzserver_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_set_header Host \$host;
|
||||||
|
proxy_set_header X-Real-IP \$remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||||
|
proxy_cache off;
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
if ! "$NGINX" -t >/tmp/xyzserver-nginx-test.log 2>&1; then
|
||||||
|
cat /tmp/xyzserver-nginx-test.log
|
||||||
|
[ -f "$REWRITE.bak.$TS" ] && mv -f "$REWRITE.bak.$TS" "$REWRITE" || rm -f "$REWRITE"
|
||||||
|
[ -f "$UPSTREAM.bak.$TS" ] && mv -f "$UPSTREAM.bak.$TS" "$UPSTREAM" || rm -f "$UPSTREAM"
|
||||||
|
fail "Nginx 配置检查不通过,已恢复原配置"
|
||||||
|
fi
|
||||||
|
"$NGINX" -s reload
|
||||||
|
rm -f "$REWRITE".bak.* "$UPSTREAM".bak.*
|
||||||
|
|
||||||
|
log "完成:$(systemctl is-active xyzserver),程序 $APP/xyzserver,数据 $APP/data"
|
||||||
@@ -0,0 +1,776 @@
|
|||||||
|
# XYZ 图层使用人数统计 — 开发文档
|
||||||
|
|
||||||
|
| 项 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| 对应需求 | `docs/PRD.md`(第 3 版)。产品规则以 PRD 为准,本文只写怎么实现 |
|
||||||
|
| 技术栈 | Go 1.25 及以上(`modernc.org/sqlite` v1.59 的要求)、标准库 `net/http`、SQLite(`modernc.org/sqlite`,纯 Go,不需要 CGO)、原生 HTML + JavaScript |
|
||||||
|
| 第三方依赖 | 只有 `modernc.org/sqlite` |
|
||||||
|
| 交付物 | 一个可执行文件(统计页打包在里面)和一个数据目录 |
|
||||||
|
|
||||||
|
文中的 Go 代码、SQL 和数据量已在 Windows、Go 1.27.1、`modernc.org/sqlite` v1.59.0 上编译并实测通过。
|
||||||
|
|
||||||
|
## 1. 开工前必读:不能改的地方
|
||||||
|
|
||||||
|
下面每一条都来自 QGIS / QField 的真实行为(PRD 第 2 节)。改了不会报错,但统计会悄悄失真。代码评审时逐条检查。
|
||||||
|
|
||||||
|
| 不能改 | 改了会怎样 |
|
||||||
|
| --- | --- |
|
||||||
|
| 瓦片响应固定带 `Cache-Control: no-store` | QGIS 会把瓦片存进磁盘缓存并永久使用,看过的区域以后不再请求 |
|
||||||
|
| cookie 必须带 `Path=/tiles/` | Qt 默认只在同一目录下回传 cookie,每个 `z/x` 目录会各拿一个 ID,人数暴涨 |
|
||||||
|
| 瓦片必须是能解码的 PNG | 空响应或错误码会让 QGIS 报错,并在每次重绘时重新请求 |
|
||||||
|
| 不按 IP 限流 | 共用出口的办公室会被整组丢掉统计 |
|
||||||
|
| 瓦片请求里不读写数据库和磁盘 | 瓦片是请求量最大的接口,只能做内存操作 |
|
||||||
|
| 不保存原始 IP 和 User-Agent,不为每张瓦片写访问日志 | 隐私要求;日志量也会远大于数据本身 |
|
||||||
|
|
||||||
|
## 2. 第一步:客户端实测
|
||||||
|
|
||||||
|
目的:确认 PRD 的核心假设,即 QGIS / QField 会带回 cookie。先完成第 5 节的瓦片接口,打开调试日志后测试。QGIS 桌面可以直接连 `http://127.0.0.1:8080`;QField 请部署到测试域名并使用 HTTPS。
|
||||||
|
|
||||||
|
调试日志:环境变量 `XYZ_DEBUG_LOG=1` 时,每个瓦片请求打印一行,包括时间、table、z/x/y、是否带 cookie、sid 前 6 位、是否下发了新 cookie、客户端 IP、User-Agent。正式运行时关闭。
|
||||||
|
|
||||||
|
测试步骤:
|
||||||
|
|
||||||
|
1. QGIS 桌面(团队实际使用的版本,需 3.22 以上)
|
||||||
|
1. 新建 XYZ 连接 `.../tiles/spike1/{z}/{x}/{y}.png`,加到地图上。
|
||||||
|
2. 看日志:首批请求没有 cookie;之后平移、缩放产生的请求都带同一个 sid。
|
||||||
|
3. 再加一个 `spike2` 图层并平移:`spike2` 的请求带的也是这个 sid。
|
||||||
|
4. 在一小块区域来回平移,请求会明显减少甚至停止。这是 QGIS 内存缓存在起作用,只需观察,不作为判定。
|
||||||
|
5. 关闭 QGIS,重新打开同一工程,回到刚才的区域:日志里重新出现这些瓦片的请求(说明没有走磁盘缓存),并且是一个新的 sid。
|
||||||
|
2. QField(Android;用到 iOS 也测)
|
||||||
|
1. 在 QGIS 里做一个只含该 XYZ 图层的工程,用 QFieldSync 或 QFieldCloud 传到手机。
|
||||||
|
2. 打开工程并平移地图,确认请求带回 cookie。
|
||||||
|
3. 从后台划掉 QField 再打开,确认出现一个新的 sid。
|
||||||
|
3. 记录每个客户端的 User-Agent 原文。
|
||||||
|
|
||||||
|
把结果填成下表,随交付一起提交:
|
||||||
|
|
||||||
|
| 客户端 | 版本 | 带回 cookie | 两个 table 同一 sid | 重启后重新请求 | User-Agent |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| QGIS(Windows) | | | | | |
|
||||||
|
| QField(Android) | | | | | |
|
||||||
|
|
||||||
|
判定:
|
||||||
|
|
||||||
|
- 全部通过:按本文继续开发。
|
||||||
|
- 某个客户端不带回 cookie:不用改代码。它会按「同一出口、同一版本算 1 人」计数(PRD 4.2),在交付文档中注明即可。
|
||||||
|
- QGIS 和 QField 都不带回 cookie,或者重启后不重新请求:停止开发,重新评审方案。
|
||||||
|
|
||||||
|
## 3. 总体结构
|
||||||
|
|
||||||
|
```text
|
||||||
|
QGIS / QField ─瓦片请求─► 瓦片接口 ──► 内存记录器 ──每 10 秒──► SQLite
|
||||||
|
(返回透明 PNG) │
|
||||||
|
统计页 ─每 15 秒─► /api/online ─(结果缓存 10 秒)─► 人数估算 ◄─┤
|
||||||
|
─点击查询─► /api/range ─────────────────────► 人数估算 ◄─┘
|
||||||
|
```
|
||||||
|
|
||||||
|
目录:
|
||||||
|
|
||||||
|
```text
|
||||||
|
xyzserver/
|
||||||
|
├── go.mod
|
||||||
|
├── main.go 读配置、打开数据库、启动 HTTP 服务、定时任务、优雅退出
|
||||||
|
├── config.go 读取环境变量
|
||||||
|
├── tile.go 瓦片接口:路径校验、cookie、指纹、透明 PNG
|
||||||
|
├── recorder.go 内存去重与批量写入
|
||||||
|
├── store.go SQLite:建表、写入、查询、清理
|
||||||
|
├── estimate.go 人数估算
|
||||||
|
├── api.go /api/online、/api/range、/healthz、统计页
|
||||||
|
├── web/index.html 统计页(用 go:embed 打包)
|
||||||
|
├── *_test.go
|
||||||
|
└── docs/
|
||||||
|
```
|
||||||
|
|
||||||
|
- 全部放在 `package main` 里,不需要拆包。模块名随意,例如 `xyzserver`。
|
||||||
|
- `.gitignore` 加上 `data/` 和编译产物。
|
||||||
|
- 国内网络下载依赖时设置 `GOPROXY=https://goproxy.cn,direct`。
|
||||||
|
- 服务内部统一通过一个 `now func() time.Time` 取当前时间,测试时替换。
|
||||||
|
|
||||||
|
## 4. 配置
|
||||||
|
|
||||||
|
全部通过环境变量设置,都有默认值。
|
||||||
|
|
||||||
|
| 变量 | 默认值 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `XYZ_LISTEN` | `127.0.0.1:8080` | 监听地址。有反向代理时只监听本机 |
|
||||||
|
| `XYZ_DATA_DIR` | `./data` | 数据目录,数据库文件为 `xyz.db` |
|
||||||
|
| `XYZ_ONLINE_MINUTES` | `15` | 在线窗口(分钟),允许 1 到 120 |
|
||||||
|
| `XYZ_TRUST_PROXY` | `false` | 为 `true` 时从 `X-Real-IP` 取客户端 IP。只在有反向代理、且 Go 端口不对外时打开 |
|
||||||
|
| `XYZ_TLS_CERT`、`XYZ_TLS_KEY` | 空 | 两个都设置时,由 Go 直接提供 HTTPS |
|
||||||
|
| `XYZ_DEBUG_LOG` | `0` | 为 `1` 时逐条打印瓦片请求,只用于第 2 节实测 |
|
||||||
|
|
||||||
|
配置不合法时启动失败并打印原因,不静默使用默认值。
|
||||||
|
|
||||||
|
固定常量(写在代码里,不做成配置):
|
||||||
|
|
||||||
|
| 常量 | 值 |
|
||||||
|
| --- | --- |
|
||||||
|
| 数据保留 | 72 小时 |
|
||||||
|
| 写库间隔 | 10 秒 |
|
||||||
|
| 在线结果缓存 | 10 秒 |
|
||||||
|
| 清理间隔 | 1 小时(启动时先执行一次) |
|
||||||
|
| 每分钟新增记录上限 | 20,000 |
|
||||||
|
| 时段起点容差 | 5 分钟 |
|
||||||
|
|
||||||
|
## 5. 瓦片接口
|
||||||
|
|
||||||
|
路由:`mux.HandleFunc("GET /tiles/", handleTile)`。Go 1.22 起,`GET` 路由也会匹配 HEAD;HEAD 照常返回响应头,但不记录。
|
||||||
|
|
||||||
|
处理顺序:校验路径 → 读取或下发 cookie → 写响应头和图片 → GET 请求交给记录器。
|
||||||
|
|
||||||
|
### 5.1 路径解析与校验
|
||||||
|
|
||||||
|
最后一段是 `{y}.png`,路由通配符表达不了,所以直接解析 `r.URL.EscapedPath()`:
|
||||||
|
|
||||||
|
1. 按 `/` 切分,必须正好 6 段:`""`、`"tiles"`、table、z、x、`"y.png"`。段数不对返回 404。
|
||||||
|
2. table:用 `url.PathUnescape` 解码,必须是合法 UTF-8,1 到 64 个字符,每个字符满足 `unicode.IsLetter`、`unicode.IsDigit`,或者是 `_`、`-`。
|
||||||
|
3. z、x:1 到 10 位 ASCII 数字;z 不超过 30。
|
||||||
|
4. 最后一段:1 到 10 位 ASCII 数字加小写 `.png`。
|
||||||
|
5. 任何一步不通过:`http.NotFound`,不下发 cookie,不记录。
|
||||||
|
|
||||||
|
查询参数一律忽略。实测 `/tiles/%E4%B8%9C%E5%8C%BA/12/3/4.png` 的 table 解码为 `东区`。
|
||||||
|
|
||||||
|
### 5.2 客户端 IP 与指纹
|
||||||
|
|
||||||
|
```go
|
||||||
|
func clientIP(r *http.Request, trustProxy bool) string {
|
||||||
|
var ip net.IP
|
||||||
|
if trustProxy {
|
||||||
|
ip = net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP")))
|
||||||
|
}
|
||||||
|
if ip == nil {
|
||||||
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||||
|
if err != nil {
|
||||||
|
host = r.RemoteAddr
|
||||||
|
}
|
||||||
|
ip = net.ParseIP(host)
|
||||||
|
}
|
||||||
|
if ip == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if v4 := ip.To4(); v4 != nil {
|
||||||
|
return v4.String()
|
||||||
|
}
|
||||||
|
return ip.Mask(net.CIDRMask(64, 128)).String()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
IPv6 只取前 64 位,因为手机和家庭网络的后 64 位会定期变化。
|
||||||
|
|
||||||
|
指纹:`HMAC-SHA256(盐, IP + "\n" + User-Agent)`,取前 8 字节,转成 16 位十六进制。User-Agent 先截到 256 字节。盐见 7.2。带 cookie 的请求也要算指纹,第一次见到某个会话时要用到。
|
||||||
|
|
||||||
|
### 5.3 cookie
|
||||||
|
|
||||||
|
- 用 `r.Cookie("sid")` 读取。值为 22 个字符、只含 `A-Z`、`a-z`、`0-9`、`-`、`_` 时视为有效。
|
||||||
|
- 有效:不再下发。
|
||||||
|
- 无效或没有:用 `crypto/rand` 生成 16 字节,经 `base64.RawURLEncoding` 编码后正好 22 个字符,然后下发:
|
||||||
|
|
||||||
|
```go
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: "sid",
|
||||||
|
Value: newID,
|
||||||
|
Path: "/tiles/",
|
||||||
|
MaxAge: 31536000,
|
||||||
|
HttpOnly: true,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
实际输出为 `Set-Cookie: sid=...; Path=/tiles/; Max-Age=31536000; HttpOnly`。
|
||||||
|
|
||||||
|
### 5.4 透明 PNG
|
||||||
|
|
||||||
|
启动时生成一次,之后每个请求直接写这段字节:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func transparentPNG() []byte {
|
||||||
|
img := image.NewPaletted(image.Rect(0, 0, 256, 256), color.Palette{color.NRGBA{}})
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := png.Encoder{CompressionLevel: png.BestCompression}
|
||||||
|
if err := enc.Encode(&buf, img); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
实测为 117 字节:1 位调色板加透明通道,解码后为 256×256、完全透明。
|
||||||
|
|
||||||
|
响应头:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Content-Type: image/png
|
||||||
|
Content-Length: 117
|
||||||
|
Cache-Control: no-store
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.5 交给记录器
|
||||||
|
|
||||||
|
GET 请求写完响应后调用:
|
||||||
|
|
||||||
|
```go
|
||||||
|
rec.Record(now, table, sid, fp) // sid 为空表示本次没带有效 cookie
|
||||||
|
```
|
||||||
|
|
||||||
|
`Record` 只操作内存,不会阻塞在数据库上。
|
||||||
|
|
||||||
|
## 6. 内存记录器
|
||||||
|
|
||||||
|
职责:把瓦片请求去重成「分钟 × table × 会话」,每 10 秒交给数据库批量写入。
|
||||||
|
|
||||||
|
- 会话标识:带了有效 cookie 就用 cookie 值;没带则用 `"~" + 指纹 + ":" + 分钟`,对应 PRD 4.1 的「该指纹在这一分钟出现过」。`~` 不在 base64url 字符集里,不会和真实 ID 冲突。
|
||||||
|
- 分钟:`Unix 秒 / 60`。
|
||||||
|
|
||||||
|
```go
|
||||||
|
const maxRowsPerMinute = 20000
|
||||||
|
|
||||||
|
type hitKey struct {
|
||||||
|
minute int64
|
||||||
|
table string
|
||||||
|
sid string
|
||||||
|
}
|
||||||
|
|
||||||
|
type sessionAgg struct {
|
||||||
|
fp string
|
||||||
|
first, last int64
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
if len(r.seen) >= maxRowsPerMinute {
|
||||||
|
r.dropped.Add(1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
if m < s.first {
|
||||||
|
s.first = m
|
||||||
|
}
|
||||||
|
if m > s.last {
|
||||||
|
s.last = m
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Take 取走待写入的数据,由写库协程每 10 秒调用一次。
|
||||||
|
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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `seen` 只保存当前分钟的键,所以内存上限约为 20,000 条。
|
||||||
|
- 写库失败时记错误日志,丢弃这一批,不重试。统计失败不能影响瓦片(PRD 第 5 节)。
|
||||||
|
|
||||||
|
## 7. 存储
|
||||||
|
|
||||||
|
### 7.1 打开数据库
|
||||||
|
|
||||||
|
```go
|
||||||
|
dsn := "file:" + filepath.ToSlash(filepath.Join(dataDir, "xyz.db")) +
|
||||||
|
"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)"
|
||||||
|
db, err := sql.Open("sqlite", dsn) // import _ "modernc.org/sqlite"
|
||||||
|
```
|
||||||
|
|
||||||
|
数据目录不存在时先创建。实测上面的写法能让 `journal_mode` 生效为 `wal`。
|
||||||
|
|
||||||
|
### 7.2 表结构
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE IF NOT EXISTS meta (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
) WITHOUT ROWID;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS hits (
|
||||||
|
minute INTEGER NOT NULL, -- Unix 秒 / 60
|
||||||
|
tbl TEXT NOT NULL,
|
||||||
|
sid TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (minute, tbl, sid)
|
||||||
|
) WITHOUT ROWID;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
sid TEXT PRIMARY KEY,
|
||||||
|
fp TEXT NOT NULL,
|
||||||
|
first_min INTEGER NOT NULL,
|
||||||
|
last_min INTEGER NOT NULL
|
||||||
|
) WITHOUT ROWID;
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS sessions_last_min ON sessions(last_min);
|
||||||
|
```
|
||||||
|
|
||||||
|
盐:启动时读取 `meta` 表中的 `fp_salt`;没有时用 `crypto/rand` 生成 32 字节,以十六进制存入。之后不要修改,否则所有指纹都会重新开始。
|
||||||
|
|
||||||
|
### 7.3 写入
|
||||||
|
|
||||||
|
每 10 秒在一个事务里完成,两条语句各用一次 `Prepare`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
INSERT OR IGNORE INTO hits(minute, tbl, sid) VALUES (?, ?, ?);
|
||||||
|
|
||||||
|
INSERT INTO sessions(sid, fp, first_min, last_min) VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT(sid) DO UPDATE SET
|
||||||
|
first_min = MIN(first_min, excluded.first_min),
|
||||||
|
last_min = MAX(last_min, excluded.last_min);
|
||||||
|
```
|
||||||
|
|
||||||
|
冲突时不更新 `fp`,会话始终使用第一次出现时的指纹。实测三次写入同一会话后,`fp` 保持第一次的值,`first_min` 取最小,`last_min` 取最大。
|
||||||
|
|
||||||
|
### 7.4 查询
|
||||||
|
|
||||||
|
在线和时段用同一条查询,参数为起止分钟(闭区间):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT h.tbl, s.sid, s.fp, s.first_min, s.last_min
|
||||||
|
FROM (SELECT DISTINCT tbl, sid FROM hits WHERE minute BETWEEN ? AND ?) AS h
|
||||||
|
JOIN sessions AS s ON s.sid = h.sid;
|
||||||
|
```
|
||||||
|
|
||||||
|
结果交给第 8 节估算。
|
||||||
|
|
||||||
|
### 7.5 清理
|
||||||
|
|
||||||
|
启动时执行一次,之后每小时执行。三条语句的参数都是 `cutoff = 当前分钟 - 72×60`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
DELETE FROM hits WHERE minute < ?;
|
||||||
|
DELETE FROM sessions WHERE last_min < ?;
|
||||||
|
UPDATE sessions SET first_min = ? WHERE first_min < ?;
|
||||||
|
```
|
||||||
|
|
||||||
|
最后一句把运行很久的会话的起点截到 72 小时以内,这只会缩短区间,不会改变估算结果。删除数据后文件不会变小,但空间会被复用,不需要 VACUUM。
|
||||||
|
|
||||||
|
### 7.6 实测数据量
|
||||||
|
|
||||||
|
用上面的表结构和 SQL 模拟 3,000 个会话、2 个 table、约 18 万条分钟记录:
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 数据库文件 | 约 8 MB |
|
||||||
|
| 查询 72 小时 | 约 0.26 秒 |
|
||||||
|
| 查询 24 小时 | 约 0.06 秒 |
|
||||||
|
| 查询 15 分钟 | 不到 1 毫秒 |
|
||||||
|
| 清理 | 约 0.02 秒 |
|
||||||
|
|
||||||
|
## 8. 人数估算
|
||||||
|
|
||||||
|
规则见 PRD 4.2。实现步骤:
|
||||||
|
|
||||||
|
1. 查询结果先按 table 分组,每个 table 内再按指纹分组。每个会话对应一个区间 `[first_min, last_min)`:包含起点那一分钟,不包含终点那一分钟。
|
||||||
|
2. 每组人数等于这些区间在同一时刻重叠的最大个数,最少为 1。`first_min == last_min` 的区间长度为 0,不参与重叠。
|
||||||
|
3. table 人数为各指纹组人数之和。
|
||||||
|
4. 全站人数:同一个会话可能出现在多个 table 里,先按会话去重,再按指纹分组,同样计算后求和。
|
||||||
|
|
||||||
|
参考实现:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type span struct{ first, last int64 } // 分钟,含 first、不含 last
|
||||||
|
|
||||||
|
// people 返回同一指纹下一组会话所需的最少人数,至少为 1。
|
||||||
|
func people(spans []span) int {
|
||||||
|
type event struct {
|
||||||
|
t int64
|
||||||
|
d int
|
||||||
|
}
|
||||||
|
events := make([]event, 0, 2*len(spans))
|
||||||
|
for _, s := range spans {
|
||||||
|
if s.last > s.first {
|
||||||
|
events = append(events, event{s.first, +1}, event{s.last, -1})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(events, func(i, j int) bool {
|
||||||
|
if events[i].t != events[j].t {
|
||||||
|
return events[i].t < events[j].t
|
||||||
|
}
|
||||||
|
return events[i].d < events[j].d // 同一分钟先结束再开始,首尾相接不算重叠
|
||||||
|
})
|
||||||
|
cur, best := 0, 1
|
||||||
|
for _, e := range events {
|
||||||
|
cur += e.d
|
||||||
|
if cur > best {
|
||||||
|
best = cur
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
type sessionRow struct {
|
||||||
|
table, sid, fp string
|
||||||
|
first, last int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
Total int
|
||||||
|
Tables map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func estimate(rows []sessionRow) result {
|
||||||
|
perTable := map[string]map[string][]span{} // table → 指纹 → 区间
|
||||||
|
global := map[string]map[string]span{} // 指纹 → 会话 → 区间
|
||||||
|
for _, r := range rows {
|
||||||
|
sp := span{r.first, r.last}
|
||||||
|
if perTable[r.table] == nil {
|
||||||
|
perTable[r.table] = map[string][]span{}
|
||||||
|
}
|
||||||
|
perTable[r.table][r.fp] = append(perTable[r.table][r.fp], sp)
|
||||||
|
if global[r.fp] == nil {
|
||||||
|
global[r.fp] = map[string]span{}
|
||||||
|
}
|
||||||
|
global[r.fp][r.sid] = sp
|
||||||
|
}
|
||||||
|
res := result{Tables: map[string]int{}}
|
||||||
|
for table, groups := range perTable {
|
||||||
|
for _, spans := range groups {
|
||||||
|
res.Tables[table] += people(spans)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bySid := range global {
|
||||||
|
spans := make([]span, 0, len(bySid))
|
||||||
|
for _, sp := range bySid {
|
||||||
|
spans = append(spans, sp)
|
||||||
|
}
|
||||||
|
res.Total += people(spans)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`people` 必须覆盖的单元测试(参考实现已全部通过):
|
||||||
|
|
||||||
|
| 用例 | 区间(分钟) | 结果 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 10 人同时在用 | 起点 540 到 549、终点都是 1080 的 10 个区间 | 10 |
|
||||||
|
| 重启,首尾在同一分钟 | [540, 720)、[720, 1080) | 1 |
|
||||||
|
| 重启,中间有间隔 | [540, 720)、[725, 1080) | 1 |
|
||||||
|
| 只有一分钟的出现 | [700, 700)、[700, 700)、[701, 701) | 1 |
|
||||||
|
| 长会话加一分钟的出现 | [540, 1080)、[720, 720) | 1 |
|
||||||
|
| 两个会话重叠 | [540, 600)、[590, 700) | 2 |
|
||||||
|
| 两个重叠再加一个接续 | [540, 600)、[590, 700)、[700, 800) | 2 |
|
||||||
|
|
||||||
|
`estimate` 的综合用例(已通过):
|
||||||
|
|
||||||
|
| table | 会话 | 指纹 | 区间 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| grid | A | fp1 | [540, 1080) |
|
||||||
|
| building | A | fp1 | [540, 1080) |
|
||||||
|
| grid | B | fp1 | [600, 900) |
|
||||||
|
| grid | C | fp2 | [100, 400) |
|
||||||
|
| grid | D | fp2 | [400, 800) |
|
||||||
|
| grid | `~fp3:700` | fp3 | [700, 700) |
|
||||||
|
|
||||||
|
期望:`grid` 为 4(fp1 两人、fp2 前后接续算 1 人、fp3 保底 1 人),`building` 为 1,全站为 4。
|
||||||
|
|
||||||
|
## 9. 统计接口
|
||||||
|
|
||||||
|
时间一律用 `time.FixedZone("CST", 8*3600)` 格式化成 RFC3339,即 `+08:00`。中国不实行夏令时,用固定时区即可,也不依赖服务器上的时区数据。
|
||||||
|
|
||||||
|
路由:`GET /api/online`、`GET /api/range`、`GET /healthz`、`GET /{$}`(只匹配根路径,其他未知路径返回 404)。
|
||||||
|
|
||||||
|
### 9.1 GET /api/online
|
||||||
|
|
||||||
|
- 窗口:`[当前分钟 - XYZ_ONLINE_MINUTES, 当前分钟]`,执行 7.4 的查询和第 8 节估算。
|
||||||
|
- 结果缓存 10 秒:用一个互斥锁保护「计算时间 + 已编码的 JSON」。缓存过期后,拿到锁的请求负责重新计算,其他请求等它算完后直接使用。没人访问时不计算。
|
||||||
|
- `tables` 按人数从高到低排列,人数相同时按名称排序。
|
||||||
|
- 响应头带 `Cache-Control: no-store`。
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"server_time": "2026-09-23T11:30:00+08:00",
|
||||||
|
"online_minutes": 15,
|
||||||
|
"total": 12,
|
||||||
|
"tables": [
|
||||||
|
{ "table": "grid", "count": 10 },
|
||||||
|
{ "table": "building", "count": 3 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
数据库出错时返回 503:`{"error":"stats_unavailable","message":"统计暂时不可用"}`。
|
||||||
|
|
||||||
|
### 9.2 GET /api/range?start=…&end=…
|
||||||
|
|
||||||
|
处理顺序:
|
||||||
|
|
||||||
|
1. 用 `time.Parse(time.RFC3339, v)` 解析。解析失败且值里有空格时,把空格换回 `+` 再试一次,因为没做 URL 编码的 `+08:00` 会变成空格。
|
||||||
|
2. 起点不早于终点 → `bad_order`。
|
||||||
|
3. 终点减起点超过 72 小时 → `range_too_long`。
|
||||||
|
4. 终点晚于当前时间 → 改成当前时间。
|
||||||
|
5. 起点早于「当前时间 - 72 小时」:早了不超过 5 分钟时,改成这个时间;否则返回 `range_too_old`,并附上 `earliest`。
|
||||||
|
6. 截断后起点不早于终点(也就是起点在未来)→ `bad_order`。
|
||||||
|
7. 起止时间各自换算成分钟(`Unix 秒 / 60`),执行 7.4 的查询和第 8 节估算。
|
||||||
|
|
||||||
|
同一时间只执行一个时段查询:用一个互斥锁包住第 7 步,其他请求排队。
|
||||||
|
|
||||||
|
| HTTP | error | message |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 400 | `bad_time` | 时间格式不正确 |
|
||||||
|
| 400 | `bad_order` | 起点必须早于终点,且不能晚于当前时间 |
|
||||||
|
| 400 | `range_too_long` | 时段不能超过 72 小时 |
|
||||||
|
| 400 | `range_too_old` | 最早只能查到 2026年/09月/20日 11时30分00秒(按实际时间填写) |
|
||||||
|
| 503 | `stats_unavailable` | 统计暂时不可用 |
|
||||||
|
|
||||||
|
`range_too_old` 额外返回 `"earliest": "2026-09-20T11:30:00+08:00"`。
|
||||||
|
|
||||||
|
成功时,`start`、`end` 是截断后实际使用的值:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"start": "2026-09-22T11:30:00+08:00",
|
||||||
|
"end": "2026-09-23T11:30:00+08:00",
|
||||||
|
"total": 25,
|
||||||
|
"tables": [
|
||||||
|
{ "table": "grid", "count": 20 },
|
||||||
|
{ "table": "building", "count": 8 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.3 其他
|
||||||
|
|
||||||
|
- `GET /{$}`:返回 `web/index.html`(`//go:embed`),带 `Content-Type: text/html; charset=utf-8` 和 `Cache-Control: no-cache`。
|
||||||
|
- `GET /healthz`:返回 200 和 `ok`,不访问数据库。
|
||||||
|
|
||||||
|
## 10. 统计页
|
||||||
|
|
||||||
|
只有一个文件 `web/index.html`,CSS 和 JS 都写在里面。不引用任何外部资源,不用前端框架。
|
||||||
|
|
||||||
|
### 10.1 时间处理
|
||||||
|
|
||||||
|
页面不使用浏览器时区,一律按北京时间:
|
||||||
|
|
||||||
|
- 服务器时间:每次收到 `/api/online` 响应时记下 `offset = Date.parse(server_time) - Date.now()`,「当前服务器时间」即 `Date.now() + offset`。
|
||||||
|
- 显示:时间戳加 8 小时后,用 `getUTCFullYear()` 等方法取各部分,格式为 `YYYY年/MM月/DD日 HH时mm分ss秒`,月、日、时、分、秒补零。
|
||||||
|
- 输入:从输入框取出 6 组数字(年、月、日、时、分、秒),所以粘贴 `2026-09-23 11:30:00` 也能识别。校验月份、日期和时分秒的范围,失焦后改写成标准格式。换算公式:`Date.UTC(年, 月-1, 日, 时, 分, 秒) - 8×3600×1000`。
|
||||||
|
- 发给接口:拼成 `YYYY-MM-DDTHH:mm:ss+08:00`,再用 `encodeURIComponent` 编码。
|
||||||
|
|
||||||
|
### 10.2 实时在线
|
||||||
|
|
||||||
|
- 打开页面立即请求一次,之后每 15 秒一次。用 `setTimeout` 串联,上一次结束后再安排下一次。
|
||||||
|
- `document.hidden` 为真时不请求;`visibilitychange` 回到可见时立即请求一次。
|
||||||
|
- 成功:显示全站人数和列表。没人在线时显示用法(见 10.4)。
|
||||||
|
- 失败:保留上次数据,在标题旁显示「更新失败 HH:mm:ss,显示的是上次数据」。
|
||||||
|
- 列表每行显示 table 名称、人数和「复制地址」按钮。
|
||||||
|
|
||||||
|
### 10.3 时段查询
|
||||||
|
|
||||||
|
- 两个输入框(起点、终点),默认填最近 1 小时,不自动查询。
|
||||||
|
- 快捷按钮「最近 1 小时」「最近 24 小时」「最近 3 天」:按服务器当前时间回填,并立即查询。
|
||||||
|
- 「查询」按钮:先在页面上做与 9.2 第 1、2、3、5 步相同的校验,起点容差也是 5 分钟。不通过时在按钮下方显示原因,不发请求。
|
||||||
|
- 查询期间按钮置灰,防止重复点击。
|
||||||
|
- 结果:全站人数、各 table 人数,以及「查询范围:起点 – 终点(查询于 HH:mm:ss)」。起止时间用接口返回的实际值。
|
||||||
|
|
||||||
|
### 10.4 用法与复制
|
||||||
|
|
||||||
|
- 页面底部固定显示地址模板 `https://当前域名/tiles/{table}/{z}/{x}/{y}.png`、一句用法说明,以及 PRD 6.3 的几条说明。
|
||||||
|
- 复制地址:`location.origin + "/tiles/" + table + "/{z}/{x}/{y}.png"`。table 只含字母、数字、`_`、`-`,可以直接拼接。优先用 `navigator.clipboard.writeText`;失败时用 `prompt()` 显示地址,让用户手动复制。
|
||||||
|
- 所有 table 名称都用 `textContent` 写入页面,不用 `innerHTML`。
|
||||||
|
|
||||||
|
## 11. 运行与退出
|
||||||
|
|
||||||
|
```go
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: cfg.Listen,
|
||||||
|
Handler: mux,
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
后台协程:
|
||||||
|
|
||||||
|
- 写库:每 10 秒调用一次 `Take()`,然后写库。
|
||||||
|
- 清理:启动时执行一次,之后每小时一次。
|
||||||
|
- 汇总日志:每 10 分钟输出一行,内容是这段时间的瓦片请求数、404 数、新下发的 cookie 数、写入行数和因上限丢弃的数量,用 `sync/atomic` 计数。
|
||||||
|
|
||||||
|
收到 SIGINT 或 SIGTERM 时按顺序:
|
||||||
|
|
||||||
|
1. 调用 `srv.Shutdown`,最多等 10 秒。
|
||||||
|
2. 最后写一次库。
|
||||||
|
3. 关闭数据库。
|
||||||
|
|
||||||
|
日志用标准库 `log/slog` 输出到标准输出。只记录启动信息、错误和汇总,不记录单个瓦片。
|
||||||
|
|
||||||
|
## 12. 部署
|
||||||
|
|
||||||
|
### 12.1 编译
|
||||||
|
|
||||||
|
PowerShell(在 Windows 上编译 Linux 版本;这些变量只对当前终端有效):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:CGO_ENABLED = "0"; $env:GOOS = "linux"; $env:GOARCH = "amd64"
|
||||||
|
go build -trimpath -ldflags "-s -w" -o xyzserver .
|
||||||
|
```
|
||||||
|
|
||||||
|
Bash:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w" -o xyzserver .
|
||||||
|
```
|
||||||
|
|
||||||
|
### 12.2 systemd
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=XYZ layer usage counter
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart=/opt/xyzserver/xyzserver
|
||||||
|
Environment=XYZ_LISTEN=127.0.0.1:8080
|
||||||
|
Environment=XYZ_DATA_DIR=/var/lib/xyzserver
|
||||||
|
Environment=XYZ_TRUST_PROXY=true
|
||||||
|
DynamicUser=yes
|
||||||
|
StateDirectory=xyzserver
|
||||||
|
Restart=on-failure
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
### 12.3 HTTPS
|
||||||
|
|
||||||
|
以下三种方式任选一种。
|
||||||
|
|
||||||
|
Caddy 会自动申请证书,最省事:
|
||||||
|
|
||||||
|
```text
|
||||||
|
统计域名 {
|
||||||
|
reverse_proxy 127.0.0.1:8080 {
|
||||||
|
header_up X-Real-IP {remote_host}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Nginx:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
upstream xyzserver {
|
||||||
|
server 127.0.0.1:8080;
|
||||||
|
keepalive 32;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name 统计域名;
|
||||||
|
ssl_certificate /path/fullchain.pem;
|
||||||
|
ssl_certificate_key /path/privkey.pem;
|
||||||
|
|
||||||
|
access_log off;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://xyzserver;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`keepalive`、`proxy_http_version 1.1` 和清空 `Connection` 三项要一起配置,否则每个瓦片请求都会在 Nginx 和 Go 之间新建一次连接。
|
||||||
|
|
||||||
|
由 Go 直接提供 HTTPS:设置 `XYZ_TLS_CERT`、`XYZ_TLS_KEY`,并设 `XYZ_LISTEN=:443`、`XYZ_TRUST_PROXY=false`。证书续期需要自己处理。
|
||||||
|
|
||||||
|
注意:
|
||||||
|
|
||||||
|
- 有反向代理时,Go 只能监听 `127.0.0.1`,否则别人可以绕过代理,伪造 `X-Real-IP`。
|
||||||
|
- 前面不要加 CDN。
|
||||||
|
- Windows 服务器也可以直接运行编译出的 exe,用 Caddy 提供 HTTPS。
|
||||||
|
|
||||||
|
### 12.4 上线检查
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -D - -o /dev/null https://统计域名/tiles/test/0/0/0.png
|
||||||
|
```
|
||||||
|
|
||||||
|
应看到 `200`、`Content-Type: image/png`、`Content-Length: 117`、`Cache-Control: no-store`,以及 `Set-Cookie: sid=...; Path=/tiles/; Max-Age=31536000; HttpOnly`。
|
||||||
|
|
||||||
|
## 13. 测试
|
||||||
|
|
||||||
|
### 13.1 单元测试
|
||||||
|
|
||||||
|
| 对象 | 要点 |
|
||||||
|
| --- | --- |
|
||||||
|
| 路径校验 | 中文 table 通过;空名、65 个字符、含空格、含 `%2F`、含 `..` 都被拒绝;z=31 被拒绝;最后一段不是「数字.png」被拒绝 |
|
||||||
|
| cookie | 22 位 base64url 有效;21 位、含 `+` 或 `/` 无效;新生成的 ID 长 22 位 |
|
||||||
|
| 指纹 | 同 IP、同 UA 结果相同;IPv6 同一 /64 前缀结果相同;UA 超过 256 字节时被截断 |
|
||||||
|
| IP | 不信任代理时忽略 `X-Real-IP`;信任时使用它;`::ffff:` 开头的地址按 IPv4 处理 |
|
||||||
|
| 透明 PNG | 能解码,256×256,每个像素 alpha 为 0,不超过 200 字节 |
|
||||||
|
| 记录器 | 同一分钟重复请求只记一行;跨分钟各记一行;无 cookie 请求使用 `~指纹:分钟`;两次 `Take` 之间同一分钟的重复请求不会再写;超过上限后丢弃并计数 |
|
||||||
|
| 存储 | upsert 后 `fp` 不变,`first_min` 取小,`last_min` 取大;清理后不存在 72 小时以前的数据 |
|
||||||
|
| 人数估算 | 第 8 节两张表的全部用例 |
|
||||||
|
| 时段校验 | 9.2 的每种错误;终点在未来时被截断;起点早 3 分钟时被改为最早可查时间,早 10 分钟时被拒绝;空格能换回 `+` |
|
||||||
|
|
||||||
|
### 13.2 接口测试
|
||||||
|
|
||||||
|
用 `httptest` 启动完整服务,数据库放在临时目录,时钟可替换:
|
||||||
|
|
||||||
|
1. 不带 cookie 请求瓦片:返回 200,有 `Set-Cookie` 且带 `Path=/tiles/`,有 `Cache-Control: no-store`。
|
||||||
|
2. 带上一步的 cookie 请求 `grid` 和 `building`:没有 `Set-Cookie`。手动触发写库后,`/api/online` 的 `total` 为 1,两个 table 各为 1。
|
||||||
|
3. 用两个不同的 cookie,以相同的 IP 和 UA 同时请求:`total` 为 2。
|
||||||
|
4. 相同 IP 和 UA:第一个 cookie 在第 0 到 5 分钟请求,第二个 cookie 在第 15 到 20 分钟请求。查询这 20 分钟,人数为 1。
|
||||||
|
|
||||||
|
### 13.3 验收
|
||||||
|
|
||||||
|
按 PRD 第 13 节逐条验证。其中第 3 到 6 条要用真实的 QGIS 做一次。
|
||||||
|
|
||||||
|
### 13.4 压测(可选)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
hey -z 30s -c 100 -H "Cookie: sid=AAAAAAAAAAAAAAAAAAAAAA" https://统计域名/tiles/load/10/1/1.png
|
||||||
|
```
|
||||||
|
|
||||||
|
期望:CPU 占用低;数据库每分钟只多出 1 行(同一会话、同一 table 已去重)。压测数据 72 小时后自动清理。
|
||||||
|
|
||||||
|
## 14. 开发顺序与参考工作量
|
||||||
|
|
||||||
|
| 阶段 | 内容 | 参考工作量 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | 瓦片接口和调试日志,完成第 2 节实测 | 1 天 |
|
||||||
|
| 2 | 记录器、SQLite 写入与清理 | 1 天 |
|
||||||
|
| 3 | 人数估算、在线和时段接口 | 1 天 |
|
||||||
|
| 4 | 统计页 | 1 天 |
|
||||||
|
| 5 | 部署、验收、压测 | 0.5 到 1 天 |
|
||||||
|
|
||||||
|
按一名熟悉 Go 的开发人员估算,总共约 5 天。第 1 阶段实测不通过时,先停下来评审,不要继续后面的阶段。
|
||||||
|
|
||||||
|
交付内容:源码和测试(`go test ./...` 全部通过)、README(编译、配置、运行)、部署配置,以及第 2 节的实测结果表。
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
# XYZ 图层使用人数统计 — 产品需求文档
|
||||||
|
|
||||||
|
| 项 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| 状态 | 待评审。只定义产品,不含实现 |
|
||||||
|
| 日期 | 2026-09-23 |
|
||||||
|
| 版本 | 第 3 版。改用 cookie 识别会话;按 QGIS 的真实缓存行为重新定义在线;去掉 Redis、WSS 和按 IP 限流 |
|
||||||
|
| 配套文档 | 开发文档见 `docs/DEV.md` |
|
||||||
|
|
||||||
|
## 1. 目标
|
||||||
|
|
||||||
|
提供一条公开的 XYZ 图层地址。任何人把它加进 QGIS 或 QField,服务端都返回透明图片,并按地址中的 `table` 统计使用人数。
|
||||||
|
|
||||||
|
- 所有人复制同一条地址,不给每个人单独的地址。
|
||||||
|
- 不修改 QGIS / QField,只用它们请求瓦片时发来的信息。
|
||||||
|
- 一台设备用了两个 `table`,两个 `table` 各算 1 人。
|
||||||
|
- 统计页无需登录,显示每个 `table` 的实时在线人数,也能查近 3 天内任意时段的人数。服务器只保留近 3 天的数据。
|
||||||
|
- 人数尽量接近真实;做不到精确的地方给估算值,并在页面上说明。
|
||||||
|
- 轻量:一个 Go 程序加一个本地数据文件,不依赖其他服务。
|
||||||
|
|
||||||
|
## 2. 设计依据:QGIS / QField 的真实行为
|
||||||
|
|
||||||
|
以下来自 QGIS 官方文档和源码(`qgsnetworkaccessmanager.cpp`、`qgstilecache.cpp`、`qgswmsprovider.cpp`)。QField 通过 QGIS 的网络库和瓦片代码请求图层,预期行为相同,开发前需实测(第 11 节)。
|
||||||
|
|
||||||
|
| 客户端行为 | 对设计的影响 |
|
||||||
|
| --- | --- |
|
||||||
|
| User-Agent 只含软件版本号和操作系统名,例如 `Mozilla/5.0 QGIS/33801/Ubuntu 22.04.4 LTS` | 同一出口 IP、同一版本的人,靠「IP + User-Agent」分不开。办公室和手机运营商网络里,会把很多人合成 1 人 |
|
||||||
|
| QGIS 3.22 起,各线程的 cookie 保持同步,只存在内存里 | 服务端下发一个随机 cookie,就能认出同一个正在运行的 QGIS / QField。重启软件后变成新会话 |
|
||||||
|
| cookie 不写 `Path` 时,Qt 只在同一目录下回传它 | 必须写 `Path=/tiles/`,否则不同 `z/x` 目录、不同 `table` 会拿到不同的 ID |
|
||||||
|
| QGIS 在内存里留着最近用过的 256 张瓦片,再次显示时直接使用,与响应头无关 | 在同一片区域反复看地图不会再请求。「在线」只能定义为最近一段时间加载过新瓦片 |
|
||||||
|
| 瓦片只要进了 QGIS 的磁盘网络缓存,以后一直从缓存取,不检查过期时间,重启后也一样 | 瓦片响应必须 `no-store`。一旦允许缓存,看过的区域以后永远不再请求,统计会悄悄失效 |
|
||||||
|
| 返回错误码或无法解码的图片时,QGIS 记错误日志,且不放进内存缓存 | 必须返回有效 PNG。返回空响应反而会让每次重绘都重新请求 |
|
||||||
|
|
||||||
|
## 3. 使用方式
|
||||||
|
|
||||||
|
图层地址:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://统计域名/tiles/{table}/{z}/{x}/{y}.png
|
||||||
|
```
|
||||||
|
|
||||||
|
把 `{table}` 换成任意名称,例如 `grid`、`东区一组`;`{z}/{x}/{y}` 原样保留。在 QGIS 里新建 XYZ 连接,或在 QField 项目里加入这个图层即可。图层是透明的,不影响底图。
|
||||||
|
|
||||||
|
一台设备要计入两个 `table`,就加两个图层,只改 `table`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://统计域名/tiles/grid/{z}/{x}/{y}.png
|
||||||
|
https://统计域名/tiles/building/{z}/{x}/{y}.png
|
||||||
|
```
|
||||||
|
|
||||||
|
统计页:`https://统计域名/`
|
||||||
|
|
||||||
|
## 4. 统计口径
|
||||||
|
|
||||||
|
### 4.1 会话
|
||||||
|
|
||||||
|
一个会话是一次运行中的 QGIS 或 QField。
|
||||||
|
|
||||||
|
- 请求没带统计 cookie:响应里用 `Set-Cookie` 下发一个新的随机会话 ID。
|
||||||
|
- 请求带了 cookie:这次请求记在该会话上,不再下发 cookie。
|
||||||
|
- 客户端第一次加载图层时会同时发出几十个请求,此时都没有 cookie。每个响应下发不同的 ID,客户端最终只留下其中一个。这批无 cookie 的请求不产生会话,只记为「该指纹在这一分钟出现过」(指纹见 4.2)。
|
||||||
|
|
||||||
|
### 4.2 从会话估算人数
|
||||||
|
|
||||||
|
会话不完全等于人:重启软件会换一个会话。因此按「指纹」把可能属于同一个人的会话合并。
|
||||||
|
|
||||||
|
指纹是客户端 IP + User-Agent 的加盐哈希,取会话第一次请求时的值。它分不开同网络、同版本的人,只用来判断几个会话有没有可能是同一个人。
|
||||||
|
|
||||||
|
规则:同一指纹下,人数取能解释这些会话的最少人数,每个出现过的指纹至少算 1 人;各指纹的人数相加。一个人同一时间只运行一个会话,前后接续的会话可以是同一个人,所以最少人数就是这些会话在同一时刻最多有几个同时存在。
|
||||||
|
|
||||||
|
时间以分钟计:会话从第一次请求的那一分钟存在到最后一次请求的那一分钟,最后一分钟不算。因此只在同一分钟首尾相接的两个会话算前后接续;只出现过一分钟的会话,以及 4.1 中无 cookie 的出现,不单独增加人数。
|
||||||
|
|
||||||
|
| 场景 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 办公室 10 人,同一出口、同一 QGIS 版本,同时在用 | 10 |
|
||||||
|
| 一个人上午开一次 QGIS,下午重启后再用 | 1 |
|
||||||
|
| 一个人在同一个 QGIS 里用 `grid` 和 `building` | 两个 table 各 1,全站 1 |
|
||||||
|
| 不支持 cookie 的客户端 | 同一出口、同一版本算 1 人 |
|
||||||
|
| 同一出口、同一版本的两个人轮班,时间不重叠 | 1(偏少) |
|
||||||
|
| 手机换网络后重开 QField | 2(偏多) |
|
||||||
|
|
||||||
|
最后两种是已知误差。页面写明「人数为估算值」。
|
||||||
|
|
||||||
|
### 4.3 实时在线
|
||||||
|
|
||||||
|
在线人数:取最近 15 分钟内有请求的会话,按 4.2 估算人数。窗口可配置。
|
||||||
|
|
||||||
|
QGIS 会直接使用内存里已有的瓦片(第 2 节),所以一直在同一片区域工作、不加载新瓦片的人,15 分钟后会显示为不在线。页面写明「在线指最近 15 分钟内加载过新瓦片」。
|
||||||
|
|
||||||
|
### 4.4 时段人数
|
||||||
|
|
||||||
|
时段人数:取所选时段内有请求的会话,按 4.2 估算人数。
|
||||||
|
|
||||||
|
- 起止时间可选到秒,统计按分钟:与时段有重叠的分钟都算入,边界约有 1 分钟误差。
|
||||||
|
- 时段最长 72 小时,起点不早于当前时间减 72 小时。终点晚于当前时间时按当前时间算。
|
||||||
|
- 起点只早了 5 分钟以内时,自动改成最早可查时间,避免页面放了一会儿后「最近 3 天」被拒绝。
|
||||||
|
- 各 table 的人数可以重叠,相加可能大于全站人数。页面另给全站人数。
|
||||||
|
|
||||||
|
### 4.5 table 名称
|
||||||
|
|
||||||
|
- 不设白名单,第一次被访问就开始统计。
|
||||||
|
- URL 解码后 1 到 64 个字符,只允许各语言的字母、数字、`_`、`-`,区分大小写。
|
||||||
|
- 不合法的名称返回 404,不计入。
|
||||||
|
|
||||||
|
## 5. 瓦片接口
|
||||||
|
|
||||||
|
`GET /tiles/{table}/{z}/{x}/{y}.png`
|
||||||
|
|
||||||
|
- `z`、`x`、`y` 为非负整数,`z` 不超过 30。所有坐标返回同一张 256×256 全透明 PNG(实测 117 字节),程序启动时放在内存里。
|
||||||
|
- 响应头固定带 `Cache-Control: no-store`,不可改为可缓存(原因见第 2 节)。
|
||||||
|
- 请求没带合法 cookie 时,加 `Set-Cookie: sid=<随机ID>; Path=/tiles/; Max-Age=31536000; HttpOnly`。`Path=/tiles/` 不可省略。
|
||||||
|
- 查询参数一律忽略。
|
||||||
|
- 瓦片请求不做磁盘和网络读写:去重在内存完成,约每 10 秒批量写入一次数据库。统计写入失败或达到上限时,照常返回图片。
|
||||||
|
|
||||||
|
## 6. 统计页
|
||||||
|
|
||||||
|
一个页面,无需登录。页面文件打包在程序里,不引用外部资源。时间一律按服务器的北京时间显示。
|
||||||
|
|
||||||
|
### 6.1 实时在线
|
||||||
|
|
||||||
|
- 顶部是全站在线人数;下面每行一个 table:名称、在线人数、「复制图层地址」按钮。只列在线人数大于 0 的 table,按人数从高到低排列。
|
||||||
|
- 没人在线时,显示图层地址的用法。
|
||||||
|
- 每 15 秒请求一次在线接口。页面切到后台时暂停,回到前台立即刷新。
|
||||||
|
- 请求失败时保留上次的数字并提示更新失败,不显示为 0。
|
||||||
|
|
||||||
|
### 6.2 时段查询
|
||||||
|
|
||||||
|
- 起止时间显示为 `xxxx年/xx月/xx日 xx时xx分xx秒`,可选到秒。快捷按钮:最近 1 小时、最近 24 小时、最近 3 天,点击后回填时间并立即查询。
|
||||||
|
- 起点不早于终点、超过 72 小时、早于最早可查时间时,页面直接提示,不发请求。
|
||||||
|
- 只有点快捷按钮或「查询」时才请求,不自动刷新。结果为全站人数和各 table 人数,并注明本次实际查询的起止时间。
|
||||||
|
|
||||||
|
### 6.3 页面上的说明
|
||||||
|
|
||||||
|
- 在线指最近 15 分钟内加载过新瓦片。
|
||||||
|
- 人数为估算值;各 table 相加可能大于全站人数。
|
||||||
|
- 只保留近 72 小时的数据。
|
||||||
|
|
||||||
|
## 7. 统计接口
|
||||||
|
|
||||||
|
| 接口 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /api/online` | 服务器时间、在线窗口分钟数、全站在线人数、各 table 在线人数。结果在服务端缓存 10 秒,多人同时查看也只计算一次 |
|
||||||
|
| `GET /api/range?start=…&end=…` | 时间为带时区的 RFC3339。返回实际使用的起止时间、全站人数、各 table 人数。同一时间只执行一个查询,其余排队 |
|
||||||
|
| `GET /` | 统计页 |
|
||||||
|
| `GET /healthz` | 进程存活检查 |
|
||||||
|
|
||||||
|
在线接口响应示例:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"server_time": "2026-09-23T11:30:00+08:00",
|
||||||
|
"online_minutes": 15,
|
||||||
|
"total": 12,
|
||||||
|
"tables": [
|
||||||
|
{ "table": "grid", "count": 10 },
|
||||||
|
{ "table": "building", "count": 3 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
时段接口响应示例:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"start": "2026-09-22T11:30:00+08:00",
|
||||||
|
"end": "2026-09-23T11:30:00+08:00",
|
||||||
|
"total": 25,
|
||||||
|
"tables": [
|
||||||
|
{ "table": "grid", "count": 20 },
|
||||||
|
{ "table": "building", "count": 8 }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
时段参数不合法时返回 400,JSON 里的 `message` 是可直接显示的中文;早于可查范围时附上最早可查时间。
|
||||||
|
|
||||||
|
## 8. 存储
|
||||||
|
|
||||||
|
一个本地 SQLite 文件:
|
||||||
|
|
||||||
|
- 分钟记录:分钟、table、会话。同一会话在同一分钟、同一 table 只有一行。4.1 中无 cookie 的出现,用「指纹 + 分钟」作为会话标识。
|
||||||
|
- 会话:会话标识、指纹、首次出现分钟、最后出现分钟。
|
||||||
|
- 指纹用的盐在首次启动时随机生成,存在同一文件里。不保存原始 IP 和 User-Agent。
|
||||||
|
|
||||||
|
每小时删除 72 小时以前的分钟记录,以及最后出现早于 72 小时的会话。
|
||||||
|
|
||||||
|
程序重启后历史仍在,在线人数直接从数据库算出;最多丢失重启前约 10 秒尚未写入的记录。
|
||||||
|
|
||||||
|
## 9. 性能与减压
|
||||||
|
|
||||||
|
- 瓦片请求只做内存判断,写出 117 字节的图片。单个 Go 进程可以支撑每秒数千次以上。
|
||||||
|
- 重复显示的瓦片由 QGIS 自己的内存缓存挡掉,只有加载新区域、换缩放级别时才请求。服务端不能再用缓存头减少请求(第 2 节)。
|
||||||
|
- 数据库只按「会话 × table × 分钟」写入,与瓦片请求次数无关。
|
||||||
|
- 统计页用普通轮询:每次返回几百字节的缓存结果,几个人同时查看也每秒不到一次请求,与瓦片请求相比可以忽略。
|
||||||
|
- 不为每张瓦片写访问日志,只记录错误。
|
||||||
|
- 全局上限:每分钟新增的分钟记录超过 20,000 条后暂停记录,瓦片照常返回,防止有人批量造 table 名称撑大数据库。不按 IP 限流,避免误伤共用出口的办公室。
|
||||||
|
|
||||||
|
## 10. 部署与配置
|
||||||
|
|
||||||
|
- 一个 Go 可执行文件和一个数据目录。使用纯 Go 的 SQLite 驱动,不依赖 CGO。
|
||||||
|
- HTTPS 由现有 Nginx / Caddy 提供,或由 Go 直接加载证书。前面不要加 CDN 缓存。
|
||||||
|
- 配置项:监听地址、数据目录、在线窗口(默认 15 分钟)、是否信任反向代理传来的客户端 IP(只在确实有反向代理时打开,否则指纹可被伪造)。完整列表见开发文档第 4 节。
|
||||||
|
|
||||||
|
## 11. 开发前验证
|
||||||
|
|
||||||
|
先用一个最小服务(返回透明图、下发 cookie、打印请求头)实测,通过后再按本文开发:
|
||||||
|
|
||||||
|
1. QGIS(团队实际使用的版本,需 3.22 以上)和 QField(Android;用到 iOS 也测):加图层并移动地图后,瓦片请求带回 cookie。
|
||||||
|
2. 同一个 QGIS 里的两个 `table` 带回同一个 cookie。
|
||||||
|
3. 响应为 `no-store` 时,重启 QGIS 后回到看过的区域,会重新请求。
|
||||||
|
4. 记录各客户端实际的 User-Agent。
|
||||||
|
|
||||||
|
若某个客户端不带回 cookie,它按 4.2 退化为「同一出口、同一版本算 1 人」,方案不用改。若 QGIS 和 QField 都不带回,需重新评审认人方式。
|
||||||
|
|
||||||
|
## 12. 不采用的做法
|
||||||
|
|
||||||
|
| 做法 | 原因 |
|
||||||
|
| --- | --- |
|
||||||
|
| 每人一条地址,或在地址里加设备参数 | 地址要公开复制 |
|
||||||
|
| 只用 IP + User-Agent 认人 | 同出口、同版本会合成 1 人。现在只用来合并重启前后的会话 |
|
||||||
|
| 允许客户端缓存瓦片以减少请求 | QGIS 会一直使用缓存,看过的区域以后不再请求 |
|
||||||
|
| 返回空响应或错误码来省流量 | QGIS 会记错误日志,并在每次重绘时重新请求;图片本身只有 117 字节 |
|
||||||
|
| Redis | 单进程加一个 SQLite 文件已足够,多一个服务就多一份运维 |
|
||||||
|
| WSS 推送在线人数 | 看统计页的人很少,轮询开销可以忽略;WSS 要额外配置反向代理、心跳和断线重连 |
|
||||||
|
| 按 IP 限流 | 办公室共用出口时,会把整组人的统计丢掉 |
|
||||||
|
|
||||||
|
## 13. 验收
|
||||||
|
|
||||||
|
1. 任意合法 `z/x/y` 返回同一张透明 PNG,带 `Cache-Control: no-store`。不合法的 table 或坐标返回 404,不计入。
|
||||||
|
2. 首次请求收到带 `Path=/tiles/` 的 cookie;之后带 cookie 的请求不再收到新 cookie。
|
||||||
|
3. 一个客户端首次加载时的几十个并发请求,只算 1 人。
|
||||||
|
4. 同一个 QGIS 用两个 table:两个 table 各 1,全站 1。
|
||||||
|
5. 同一出口、同一 QGIS 版本的两台电脑同时使用:计 2。
|
||||||
|
6. 同一台电脑重启 QGIS 后继续使用:在线人数和时段人数仍为 1。
|
||||||
|
7. 15 分钟没有新请求后,从在线人数中消失;包含那段时间的时段人数仍然算它。
|
||||||
|
8. 时段刚好 72 小时可以查;超过 72 小时或早于可查范围被拒绝,并有中文提示。
|
||||||
|
9. 72 小时以前的数据被删除。
|
||||||
|
10. 统计页只在可见时轮询在线人数;时段只在点击时查询。
|
||||||
|
11. 数据库中没有原始 IP 和 User-Agent。
|
||||||
|
12. 服务重启后历史人数仍在,在线人数立即可用。
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "sort"
|
||||||
|
|
||||||
|
type span struct{ first, last int64 } // 分钟,含 first、不含 last
|
||||||
|
|
||||||
|
type event struct {
|
||||||
|
t int64
|
||||||
|
d int
|
||||||
|
}
|
||||||
|
|
||||||
|
// people 返回同一指纹下一组会话所需的最少人数,至少为 1。
|
||||||
|
func people(spans []span) int {
|
||||||
|
events := make([]event, 0, 2*len(spans))
|
||||||
|
for _, s := range spans {
|
||||||
|
if s.last > s.first {
|
||||||
|
events = append(events, event{s.first, +1}, event{s.last, -1})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(events, func(i, j int) bool {
|
||||||
|
if events[i].t != events[j].t {
|
||||||
|
return events[i].t < events[j].t
|
||||||
|
}
|
||||||
|
return events[i].d < events[j].d // 同一分钟先结束再开始,首尾相接不算重叠
|
||||||
|
})
|
||||||
|
cur, best := 0, 1
|
||||||
|
for _, e := range events {
|
||||||
|
cur += e.d
|
||||||
|
if cur > best {
|
||||||
|
best = cur
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best
|
||||||
|
}
|
||||||
|
|
||||||
|
type sessionRow struct {
|
||||||
|
table, sid, fp string
|
||||||
|
first, last int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
Total int
|
||||||
|
Tables map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func estimate(rows []sessionRow) result {
|
||||||
|
perTable := map[string]map[string][]span{} // table → 指纹 → 区间
|
||||||
|
global := map[string]map[string]span{} // 指纹 → 会话 → 区间
|
||||||
|
for _, r := range rows {
|
||||||
|
sp := span{r.first, r.last}
|
||||||
|
if perTable[r.table] == nil {
|
||||||
|
perTable[r.table] = map[string][]span{}
|
||||||
|
}
|
||||||
|
perTable[r.table][r.fp] = append(perTable[r.table][r.fp], sp)
|
||||||
|
if global[r.fp] == nil {
|
||||||
|
global[r.fp] = map[string]span{}
|
||||||
|
}
|
||||||
|
global[r.fp][r.sid] = sp
|
||||||
|
}
|
||||||
|
res := result{Tables: map[string]int{}}
|
||||||
|
for table, groups := range perTable {
|
||||||
|
for _, spans := range groups {
|
||||||
|
res.Tables[table] += people(spans)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bySid := range global {
|
||||||
|
spans := make([]span, 0, len(bySid))
|
||||||
|
for _, sp := range bySid {
|
||||||
|
spans = append(spans, sp)
|
||||||
|
}
|
||||||
|
res.Total += people(spans)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestPeople(t *testing.T) {
|
||||||
|
ten := make([]span, 10)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
ten[i] = span{first: 540 + int64(i), last: 1080}
|
||||||
|
}
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
spans []span
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{"ten simultaneous", ten, 10},
|
||||||
|
{"restart abut", []span{{540, 720}, {720, 1080}}, 1},
|
||||||
|
{"restart gap", []span{{540, 720}, {725, 1080}}, 1},
|
||||||
|
{"one minute", []span{{700, 700}, {700, 700}, {701, 701}}, 1},
|
||||||
|
{"long plus blip", []span{{540, 1080}, {720, 720}}, 1},
|
||||||
|
{"overlap", []span{{540, 600}, {590, 700}}, 2},
|
||||||
|
{"overlap then abut", []span{{540, 600}, {590, 700}, {700, 800}}, 2},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
if got := people(tc.spans); got != tc.want {
|
||||||
|
t.Fatalf("got %d want %d", got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEstimate(t *testing.T) {
|
||||||
|
rows := []sessionRow{
|
||||||
|
{table: "grid", sid: "A", fp: "fp1", first: 540, last: 1080},
|
||||||
|
{table: "building", sid: "A", fp: "fp1", first: 540, last: 1080},
|
||||||
|
{table: "grid", sid: "B", fp: "fp1", first: 600, last: 900},
|
||||||
|
{table: "grid", sid: "C", fp: "fp2", first: 100, last: 400},
|
||||||
|
{table: "grid", sid: "D", fp: "fp2", first: 400, last: 800},
|
||||||
|
{table: "grid", sid: "~fp3:700", fp: "fp3", first: 700, last: 700},
|
||||||
|
}
|
||||||
|
res := estimate(rows)
|
||||||
|
if res.Tables["grid"] != 4 || res.Tables["building"] != 1 || res.Total != 4 {
|
||||||
|
t.Fatalf("grid=%d building=%d total=%d", res.Tables["grid"], res.Tables["building"], res.Total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSortedTables(t *testing.T) {
|
||||||
|
got := sortedTables(map[string]int{"b": 1, "a": 2, "c": 2, "z": 0})
|
||||||
|
if len(got) != 3 || got[0].Table != "a" || got[0].Count != 2 || got[1].Table != "c" || got[2].Table != "b" {
|
||||||
|
t.Fatalf("%+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
module xyzserver
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require modernc.org/sqlite v1.59.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
modernc.org/libc v1.75.7 // indirect
|
||||||
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
modernc.org/memory v1.12.1 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
|
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||||
|
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||||
|
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||||
|
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||||
|
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||||
|
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
|
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||||
|
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||||
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||||
|
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||||
|
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
|
||||||
|
modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||||
|
modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=
|
||||||
|
modernc.org/ccgo/v4 v4.35.0/go.mod h1:qrVGs9S3Sr2Ztcg9ve+kTAYMp5a3YvWjo+SoN06kJ5I=
|
||||||
|
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||||
|
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||||
|
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||||
|
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||||
|
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
|
||||||
|
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||||
|
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||||
|
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||||
|
modernc.org/libc v1.75.7 h1:o3DTP9/0p9pKmY2WCKQaySW6wIiZhNM7wc2lUoyhfew=
|
||||||
|
modernc.org/libc v1.75.7/go.mod h1:bO5o2ztHxBb2rjz0PgdHN0sSMw57CgxGFLZ3Qd/QpVQ=
|
||||||
|
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||||
|
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||||
|
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||||
|
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||||
|
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||||
|
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||||
|
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||||
|
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||||
|
modernc.org/sqlite v1.59.0 h1:X1es1GpqBlS/5T+vbM4HLUdaa8OtQx468DF2vrx+38A=
|
||||||
|
modernc.org/sqlite v1.59.0/go.mod h1:+paeT2A3iPRHkQDwG7oA6Tk0zQd5woMEI8q7orfry8k=
|
||||||
|
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||||
|
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||||
|
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||||
|
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// App 是统计服务。now 可替换,测试用来控制时钟。
|
||||||
|
type App struct {
|
||||||
|
cfg Config
|
||||||
|
store *Store
|
||||||
|
rec *Recorder
|
||||||
|
now func() time.Time
|
||||||
|
png []byte
|
||||||
|
salt []byte
|
||||||
|
|
||||||
|
handler http.Handler
|
||||||
|
|
||||||
|
tiles atomic.Int64
|
||||||
|
ignored atomic.Int64
|
||||||
|
notFound atomic.Int64
|
||||||
|
newCookies atomic.Int64
|
||||||
|
written atomic.Int64
|
||||||
|
|
||||||
|
onlineMu sync.Mutex
|
||||||
|
onlineAt time.Time
|
||||||
|
onlineJSON []byte
|
||||||
|
|
||||||
|
rangeMu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewApp(cfg Config, now func() time.Time) (*App, error) {
|
||||||
|
if now == nil {
|
||||||
|
now = time.Now
|
||||||
|
}
|
||||||
|
st, err := OpenStore(cfg.DataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
salt, err := st.Salt(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
_ = st.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
a := &App{
|
||||||
|
cfg: cfg,
|
||||||
|
store: st,
|
||||||
|
rec: NewRecorder(),
|
||||||
|
now: now,
|
||||||
|
png: transparentPNG(),
|
||||||
|
salt: salt,
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("GET /tiles/", a.handleTile)
|
||||||
|
mux.HandleFunc("GET /api/online", a.handleOnline)
|
||||||
|
mux.HandleFunc("GET /api/range", a.handleRange)
|
||||||
|
mux.HandleFunc("GET /healthz", a.handleHealth)
|
||||||
|
mux.HandleFunc("GET /{$}", a.handleIndex)
|
||||||
|
a.handler = mux
|
||||||
|
return a, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Handler() http.Handler { return a.handler }
|
||||||
|
|
||||||
|
func (a *App) Close() error { return a.store.Close() }
|
||||||
|
|
||||||
|
func (a *App) Flush(ctx context.Context) error {
|
||||||
|
hits, sessions := a.rec.Take()
|
||||||
|
if len(hits) == 0 && len(sessions) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
n, err := a.store.WriteBatch(ctx, hits, sessions)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.written.Add(int64(n))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) CleanupNow(ctx context.Context) error {
|
||||||
|
cutoff := a.now().Unix()/60 - int64(retainDuration/time.Minute)
|
||||||
|
return a.store.Cleanup(ctx, cutoff)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) loopWrite(ctx context.Context) {
|
||||||
|
t := time.NewTicker(flushEvery)
|
||||||
|
defer t.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
if err := a.Flush(context.Background()); err != nil {
|
||||||
|
slog.Error("写库失败", "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) loopCleanup(ctx context.Context) {
|
||||||
|
t := time.NewTicker(cleanupEvery)
|
||||||
|
defer t.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
if err := a.CleanupNow(context.Background()); err != nil {
|
||||||
|
slog.Error("清理失败", "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type summarySnap struct {
|
||||||
|
tiles, ignored, notFound, cookies, written, dropped int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) snapshot() summarySnap {
|
||||||
|
return summarySnap{
|
||||||
|
tiles: a.tiles.Load(),
|
||||||
|
ignored: a.ignored.Load(),
|
||||||
|
notFound: a.notFound.Load(),
|
||||||
|
cookies: a.newCookies.Load(),
|
||||||
|
written: a.written.Load(),
|
||||||
|
dropped: a.rec.Dropped(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) loopSummary(ctx context.Context) {
|
||||||
|
t := time.NewTicker(summaryEvery)
|
||||||
|
defer t.Stop()
|
||||||
|
prev := a.snapshot()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
cur := a.snapshot()
|
||||||
|
slog.Info("汇总",
|
||||||
|
"瓦片请求", cur.tiles-prev.tiles,
|
||||||
|
"不计入", cur.ignored-prev.ignored,
|
||||||
|
"404", cur.notFound-prev.notFound,
|
||||||
|
"新cookie", cur.cookies-prev.cookies,
|
||||||
|
"写入行数", cur.written-prev.written,
|
||||||
|
"丢弃", cur.dropped-prev.dropped,
|
||||||
|
)
|
||||||
|
prev = cur
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, nil)))
|
||||||
|
cfg, err := loadConfig()
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("配置无效", "err", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := serve(cfg); err != nil {
|
||||||
|
slog.Error("服务退出", "err", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serve(cfg Config) error {
|
||||||
|
app, err := NewApp(cfg, time.Now)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer app.Close()
|
||||||
|
|
||||||
|
if err := app.CleanupNow(context.Background()); err != nil {
|
||||||
|
slog.Error("启动清理失败", "err", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: cfg.Listen,
|
||||||
|
Handler: app.Handler(),
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
}
|
||||||
|
if cfg.TLSCert != "" {
|
||||||
|
cert, err := tls.LoadX509KeyPair(cfg.TLSCert, cfg.TLSKey)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("加载证书: %w", err)
|
||||||
|
}
|
||||||
|
srv.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||||
|
}
|
||||||
|
ln, err := net.Listen("tcp", cfg.Listen)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("监听 %s: %w", cfg.Listen, err)
|
||||||
|
}
|
||||||
|
slog.Info("服务已启动", "listen", cfg.Listen, "tls", srv.TLSConfig != nil, "data", cfg.DataDir, "online_minutes", cfg.OnlineMinutes)
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
bgCtx, bgCancel := context.WithCancel(context.Background())
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Add(4)
|
||||||
|
go func() { defer wg.Done(); app.loopWrite(bgCtx) }()
|
||||||
|
go func() { defer wg.Done(); app.loopCleanup(bgCtx) }()
|
||||||
|
go func() { defer wg.Done(); app.loopSummary(bgCtx) }()
|
||||||
|
go func() { defer wg.Done(); app.loopOnline(bgCtx) }()
|
||||||
|
|
||||||
|
errCh := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
if srv.TLSConfig != nil {
|
||||||
|
errCh <- srv.ServeTLS(ln, "", "")
|
||||||
|
} else {
|
||||||
|
errCh <- srv.Serve(ln)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
case err := <-errCh:
|
||||||
|
bgCancel()
|
||||||
|
wg.Wait()
|
||||||
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("正在关闭")
|
||||||
|
shutCtx, cancel := context.WithTimeout(context.Background(), shutdownFor)
|
||||||
|
defer cancel()
|
||||||
|
if err := srv.Shutdown(shutCtx); err != nil {
|
||||||
|
slog.Error("HTTP 关闭未完成", "err", err)
|
||||||
|
}
|
||||||
|
bgCancel()
|
||||||
|
wg.Wait()
|
||||||
|
if err := app.Flush(context.Background()); err != nil {
|
||||||
|
slog.Error("最后写库失败", "err", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
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) {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
if len(r.seen) >= maxRowsPerMinute {
|
||||||
|
r.dropped.Add(1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
if m < s.first {
|
||||||
|
s.first = m
|
||||||
|
}
|
||||||
|
if m > s.last {
|
||||||
|
s.last = m
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRecorderDedup(t *testing.T) {
|
||||||
|
r := NewRecorder()
|
||||||
|
m0 := time.Unix(100*60, 0)
|
||||||
|
m1 := time.Unix(101*60, 0)
|
||||||
|
|
||||||
|
r.Record(m0, "grid", "sid", "fp")
|
||||||
|
r.Record(m0, "grid", "sid", "fp")
|
||||||
|
hits, sessions := r.Take()
|
||||||
|
if len(hits) != 1 {
|
||||||
|
t.Fatalf("same minute rows %d", len(hits))
|
||||||
|
}
|
||||||
|
if sessions["sid"] == nil || sessions["sid"].first != 100 || sessions["sid"].last != 100 {
|
||||||
|
t.Fatalf("session %+v", sessions["sid"])
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Record(m0, "grid", "sid", "fp")
|
||||||
|
hits, _ = r.Take()
|
||||||
|
if len(hits) != 0 {
|
||||||
|
t.Fatalf("duplicate between takes wrote %d", len(hits))
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Record(m0, "grid", "other", "fp")
|
||||||
|
r.Record(m1, "grid", "other", "fp")
|
||||||
|
hits, sessions = r.Take()
|
||||||
|
if len(hits) != 2 {
|
||||||
|
t.Fatalf("cross minute rows %d", len(hits))
|
||||||
|
}
|
||||||
|
if sessions["other"] == nil || sessions["other"].first != 100 || sessions["other"].last != 101 {
|
||||||
|
t.Fatalf("cross minute session %+v", sessions["other"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecorderAnonymousSID(t *testing.T) {
|
||||||
|
r := NewRecorder()
|
||||||
|
now := time.Unix(100*60, 0)
|
||||||
|
r.Record(now, "grid", "", "abcd")
|
||||||
|
hits, sessions := r.Take()
|
||||||
|
if len(hits) != 1 || hits[0].sid != "~abcd:100" {
|
||||||
|
t.Fatalf("hits %+v", hits)
|
||||||
|
}
|
||||||
|
if sessions["~abcd:100"] == nil || sessions["~abcd:100"].fp != "abcd" {
|
||||||
|
t.Fatalf("session %+v", sessions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecorderLimit(t *testing.T) {
|
||||||
|
r := NewRecorder()
|
||||||
|
now := time.Unix(1000*60, 0)
|
||||||
|
for i := 0; i < maxRowsPerMinute; i++ {
|
||||||
|
r.Record(now, "t", strconv.Itoa(i), "fp")
|
||||||
|
}
|
||||||
|
if r.Dropped() != 0 {
|
||||||
|
t.Fatalf("dropped %d before overflow", r.Dropped())
|
||||||
|
}
|
||||||
|
r.Record(now, "t", "0", "fp")
|
||||||
|
if r.Dropped() != 0 {
|
||||||
|
t.Fatal("duplicate should not count as dropped")
|
||||||
|
}
|
||||||
|
r.Record(now, "t", "overflow", "fp")
|
||||||
|
if r.Dropped() != 1 {
|
||||||
|
t.Fatalf("dropped %d", r.Dropped())
|
||||||
|
}
|
||||||
|
hits, _ := r.Take()
|
||||||
|
if len(hits) != maxRowsPerMinute {
|
||||||
|
t.Fatalf("kept %d", len(hits))
|
||||||
|
}
|
||||||
|
|
||||||
|
r.Record(now.Add(time.Minute), "t", "overflow", "fp")
|
||||||
|
hits, _ = r.Take()
|
||||||
|
if len(hits) != 1 {
|
||||||
|
t.Fatalf("next minute %d", len(hits))
|
||||||
|
}
|
||||||
|
if r.Dropped() != 1 {
|
||||||
|
t.Fatalf("dropped changed to %d", r.Dropped())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func flushAndRefresh(t *testing.T, app *App) {
|
||||||
|
t.Helper()
|
||||||
|
if err := app.Flush(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.refreshOnline(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestApp(t *testing.T, now func() time.Time) *App {
|
||||||
|
t.Helper()
|
||||||
|
app, err := NewApp(Config{
|
||||||
|
Listen: "127.0.0.1:0",
|
||||||
|
DataDir: t.TempDir(),
|
||||||
|
OnlineMinutes: 15,
|
||||||
|
}, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = app.Close() })
|
||||||
|
return app
|
||||||
|
}
|
||||||
|
|
||||||
|
func doReq(t *testing.T, method, rawURL, sid, ua string) (int, http.Header, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
req, err := http.NewRequest(method, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if sid != "" {
|
||||||
|
req.AddCookie(&http.Cookie{Name: "sid", Value: sid})
|
||||||
|
}
|
||||||
|
if ua != "" {
|
||||||
|
req.Header.Set("User-Agent", ua)
|
||||||
|
}
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
body, err := io.ReadAll(res.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return res.StatusCode, res.Header.Clone(), body
|
||||||
|
}
|
||||||
|
|
||||||
|
func sidFromSetCookie(h http.Header) string {
|
||||||
|
raw := h.Get("Set-Cookie")
|
||||||
|
const p = "sid="
|
||||||
|
if !strings.HasPrefix(raw, p) {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
rest := raw[len(p):]
|
||||||
|
if i := strings.IndexByte(rest, ';'); i >= 0 {
|
||||||
|
rest = rest[:i]
|
||||||
|
}
|
||||||
|
return rest
|
||||||
|
}
|
||||||
|
|
||||||
|
type onlineJSON struct {
|
||||||
|
ServerTime string `json:"server_time"`
|
||||||
|
OnlineMinutes int `json:"online_minutes"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Tables []tableCount `json:"tables"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func getOnline(t *testing.T, base string) onlineJSON {
|
||||||
|
t.Helper()
|
||||||
|
res, err := http.Get(base + "/api/online")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
if res.StatusCode != 200 {
|
||||||
|
b, _ := io.ReadAll(res.Body)
|
||||||
|
t.Fatalf("online %d %s", res.StatusCode, b)
|
||||||
|
}
|
||||||
|
if res.Header.Get("Cache-Control") != "no-store" {
|
||||||
|
t.Fatalf("cache %s", res.Header.Get("Cache-Control"))
|
||||||
|
}
|
||||||
|
var body onlineJSON
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
|
||||||
|
func countsOf(tables []tableCount) map[string]int {
|
||||||
|
out := map[string]int{}
|
||||||
|
for _, row := range tables {
|
||||||
|
out[row.Table] = row.Count
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTileCookieAndOnline(t *testing.T) {
|
||||||
|
baseTime := time.Date(2026, 9, 23, 9, 0, 0, 0, cst)
|
||||||
|
clock := baseTime
|
||||||
|
app := newTestApp(t, func() time.Time { return clock })
|
||||||
|
ts := httptest.NewServer(app.Handler())
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
ua := "Mozilla/5.0 QGIS/33801/Windows"
|
||||||
|
|
||||||
|
code, hdr, body := doReq(t, http.MethodGet, ts.URL+"/tiles/grid/0/0/0.png?foo=1", "", ua)
|
||||||
|
if code != 200 {
|
||||||
|
t.Fatalf("status %d", code)
|
||||||
|
}
|
||||||
|
if hdr.Get("Content-Type") != "image/png" {
|
||||||
|
t.Fatalf("type %s", hdr.Get("Content-Type"))
|
||||||
|
}
|
||||||
|
if hdr.Get("Cache-Control") != "no-store" {
|
||||||
|
t.Fatalf("cache %s", hdr.Get("Cache-Control"))
|
||||||
|
}
|
||||||
|
if hdr.Get("Content-Length") != strconv.Itoa(len(body)) || !bytes.Equal(body, app.png) {
|
||||||
|
t.Fatalf("body %d png %d", len(body), len(app.png))
|
||||||
|
}
|
||||||
|
setCookie := hdr.Get("Set-Cookie")
|
||||||
|
if !strings.Contains(setCookie, "Path=/tiles/") || !strings.Contains(setCookie, "Max-Age=31536000") || !strings.Contains(setCookie, "HttpOnly") {
|
||||||
|
t.Fatalf("set-cookie %s", setCookie)
|
||||||
|
}
|
||||||
|
sid := sidFromSetCookie(hdr)
|
||||||
|
if !validSID(sid) {
|
||||||
|
t.Fatalf("sid %q", sid)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, hdr, _ = doReq(t, http.MethodGet, ts.URL+"/tiles/grid/31/0/0.png", "", ua)
|
||||||
|
if code != 404 || hdr.Get("Set-Cookie") != "" {
|
||||||
|
t.Fatalf("bad z status %d cookie %q", code, hdr.Get("Set-Cookie"))
|
||||||
|
}
|
||||||
|
|
||||||
|
code, hdr, body = doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/3.png", sid, ua)
|
||||||
|
if code != 200 || hdr.Get("Set-Cookie") != "" || !bytes.Equal(body, app.png) {
|
||||||
|
t.Fatalf("grid with cookie status %d cookie %q", code, hdr.Get("Set-Cookie"))
|
||||||
|
}
|
||||||
|
code, hdr, body = doReq(t, http.MethodGet, ts.URL+"/tiles/building/1/2/4.png", sid, ua)
|
||||||
|
if code != 200 || hdr.Get("Set-Cookie") != "" || !bytes.Equal(body, app.png) {
|
||||||
|
t.Fatalf("building status %d cookie %q", code, hdr.Get("Set-Cookie"))
|
||||||
|
}
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
online := getOnline(t, ts.URL)
|
||||||
|
if online.Total != 2 || online.OnlineMinutes != 15 || !strings.Contains(online.ServerTime, "+08:00") {
|
||||||
|
t.Fatalf("%+v", online)
|
||||||
|
}
|
||||||
|
got := countsOf(online.Tables)
|
||||||
|
if got["grid"] != 1 || got["building"] != 1 || len(got) != 2 {
|
||||||
|
t.Fatalf("%+v", online.Tables)
|
||||||
|
}
|
||||||
|
if online.Tables[0].Table != "building" || online.Tables[1].Table != "grid" {
|
||||||
|
t.Fatalf("order %+v", online.Tables)
|
||||||
|
}
|
||||||
|
|
||||||
|
var fp, storedSID string
|
||||||
|
if err := app.store.db.QueryRow(`SELECT sid, fp FROM sessions WHERE sid = ?`, sid).Scan(&storedSID, &fp); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(fp, ua) || strings.Contains(fp, "127.0.0.1") {
|
||||||
|
t.Fatalf("raw client data stored in fp %s", fp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTwoCookiesSameFingerprint(t *testing.T) {
|
||||||
|
// 只在同一分钟出现一次的会话区间长度是 0,不会把重叠人数抬高。
|
||||||
|
// 两个会话要算成 2 人,需要各自跨过至少两分钟并且时间重叠。
|
||||||
|
baseTime := time.Date(2026, 9, 23, 9, 0, 0, 0, cst)
|
||||||
|
clock := baseTime
|
||||||
|
app := newTestApp(t, func() time.Time { return clock })
|
||||||
|
ts := httptest.NewServer(app.Handler())
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
ua := "Mozilla/5.0 QGIS/33801/Windows"
|
||||||
|
c1 := strings.Repeat("A", 22)
|
||||||
|
c2 := strings.Repeat("B", 22)
|
||||||
|
for _, sid := range []string{c1, c2} {
|
||||||
|
clock = baseTime
|
||||||
|
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/3.png", sid, ua)
|
||||||
|
clock = baseTime.Add(time.Minute)
|
||||||
|
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/4.png", sid, ua)
|
||||||
|
}
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
online := getOnline(t, ts.URL)
|
||||||
|
if online.Total != 2 || countsOf(online.Tables)["grid"] != 2 {
|
||||||
|
t.Fatalf("%+v", online)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSequentialSessionsCountOne(t *testing.T) {
|
||||||
|
baseTime := time.Date(2026, 9, 23, 8, 0, 0, 0, cst)
|
||||||
|
clock := baseTime
|
||||||
|
app := newTestApp(t, func() time.Time { return clock })
|
||||||
|
ts := httptest.NewServer(app.Handler())
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
ua := "Mozilla/5.0 QGIS/33801/Windows"
|
||||||
|
c1 := strings.Repeat("C", 22)
|
||||||
|
c2 := strings.Repeat("D", 22)
|
||||||
|
hit := func(at time.Time, sid string) {
|
||||||
|
t.Helper()
|
||||||
|
clock = at
|
||||||
|
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/1/1.png", sid, ua)
|
||||||
|
}
|
||||||
|
hit(baseTime, c1)
|
||||||
|
hit(baseTime.Add(5*time.Minute), c1)
|
||||||
|
hit(baseTime.Add(15*time.Minute), c2)
|
||||||
|
hit(baseTime.Add(20*time.Minute), c2)
|
||||||
|
clock = baseTime.Add(20 * time.Minute)
|
||||||
|
if err := app.Flush(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
q := url.Values{}
|
||||||
|
q.Set("start", baseTime.Format(time.RFC3339))
|
||||||
|
q.Set("end", baseTime.Add(20*time.Minute).Format(time.RFC3339))
|
||||||
|
res, err := http.Get(ts.URL + "/api/range?" + q.Encode())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
if res.StatusCode != 200 {
|
||||||
|
b, _ := io.ReadAll(res.Body)
|
||||||
|
t.Fatalf("range %d %s", res.StatusCode, b)
|
||||||
|
}
|
||||||
|
var body rangeResp
|
||||||
|
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body.Total != 1 || countsOf(body.Tables)["grid"] != 1 {
|
||||||
|
t.Fatalf("%+v", body)
|
||||||
|
}
|
||||||
|
if !strings.Contains(body.Start, "+08:00") || !strings.Contains(body.End, "+08:00") {
|
||||||
|
t.Fatalf("times %s %s", body.Start, body.End)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOnlyQGISOverHTTPSCounted(t *testing.T) {
|
||||||
|
now := func() time.Time { return time.Date(2026, 9, 23, 16, 0, 0, 0, cst) }
|
||||||
|
app, err := NewApp(Config{
|
||||||
|
Listen: "127.0.0.1:0",
|
||||||
|
DataDir: t.TempDir(),
|
||||||
|
OnlineMinutes: 15,
|
||||||
|
TrustProxy: true,
|
||||||
|
HTTPSOnly: true,
|
||||||
|
}, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = app.Close() })
|
||||||
|
|
||||||
|
hit := func(table, ua, proto string) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/tiles/"+table+"/1/2/3.png", nil)
|
||||||
|
req.Header.Set("User-Agent", ua)
|
||||||
|
if proto != "" {
|
||||||
|
req.Header.Set("X-Forwarded-Proto", proto)
|
||||||
|
}
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
app.Handler().ServeHTTP(rr, req)
|
||||||
|
if rr.Code != 200 || !bytes.Equal(rr.Body.Bytes(), app.png) {
|
||||||
|
t.Fatalf("%s: status %d", table, rr.Code)
|
||||||
|
}
|
||||||
|
return rr
|
||||||
|
}
|
||||||
|
hit("qgis", "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2", "https")
|
||||||
|
hit("qfield", "Mozilla/5.0 QField/4.2.0 QGIS/34405/Android 14", "https")
|
||||||
|
hit("plainhttp", "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2", "http")
|
||||||
|
hit("noproto", "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2", "")
|
||||||
|
hit("browser", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/99.0 Safari/537.36", "https")
|
||||||
|
if rr := hit("curl", "curl/8.13.0", "https"); rr.Header().Get("Set-Cookie") == "" {
|
||||||
|
t.Fatal("uncounted clients still get a cookie")
|
||||||
|
}
|
||||||
|
if err := app.Flush(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := app.refreshOnline(context.Background()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
app.Handler().ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/api/online", nil))
|
||||||
|
var online onlineJSON
|
||||||
|
if err := json.Unmarshal(rr.Body.Bytes(), &online); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := countsOf(online.Tables)
|
||||||
|
if len(got) != 2 || got["qgis"] != 1 || got["qfield"] != 1 {
|
||||||
|
t.Fatalf("%+v", online.Tables)
|
||||||
|
}
|
||||||
|
if app.ignored.Load() != 4 {
|
||||||
|
t.Fatalf("ignored %d", app.ignored.Load())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHeadDoesNotRecord(t *testing.T) {
|
||||||
|
app := newTestApp(t, func() time.Time { return time.Date(2026, 9, 23, 9, 0, 0, 0, cst) })
|
||||||
|
ts := httptest.NewServer(app.Handler())
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
code, hdr, body := doReq(t, http.MethodHead, ts.URL+"/tiles/grid/1/2/3.png", "", "ua")
|
||||||
|
if code != 200 {
|
||||||
|
t.Fatalf("status %d", code)
|
||||||
|
}
|
||||||
|
if hdr.Get("Cache-Control") != "no-store" || hdr.Get("Content-Type") != "image/png" {
|
||||||
|
t.Fatalf("headers %v", hdr)
|
||||||
|
}
|
||||||
|
if hdr.Get("Content-Length") != strconv.Itoa(len(app.png)) {
|
||||||
|
t.Fatalf("content-length %s", hdr.Get("Content-Length"))
|
||||||
|
}
|
||||||
|
if len(body) != 0 {
|
||||||
|
t.Fatalf("head body %d", len(body))
|
||||||
|
}
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
online := getOnline(t, ts.URL)
|
||||||
|
if online.Total != 0 || len(online.Tables) != 0 {
|
||||||
|
t.Fatalf("%+v", online)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOnlineCacheAndEmpty(t *testing.T) {
|
||||||
|
baseTime := time.Date(2026, 9, 23, 12, 0, 0, 0, cst)
|
||||||
|
clock := baseTime
|
||||||
|
app := newTestApp(t, func() time.Time { return clock })
|
||||||
|
ts := httptest.NewServer(app.Handler())
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
first := getOnline(t, ts.URL)
|
||||||
|
if first.Total != 0 || first.OnlineMinutes != 15 || len(first.Tables) != 0 {
|
||||||
|
t.Fatalf("%+v", first)
|
||||||
|
}
|
||||||
|
raw, err := http.Get(ts.URL + "/api/online")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
buf, _ := io.ReadAll(raw.Body)
|
||||||
|
raw.Body.Close()
|
||||||
|
if !bytes.Contains(buf, []byte(`"tables":[]`)) {
|
||||||
|
t.Fatalf("tables not empty array: %s", buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
sid := strings.Repeat("E", 22)
|
||||||
|
ua := "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2"
|
||||||
|
doReq(t, http.MethodGet, ts.URL+"/tiles/grid/1/2/3.png", sid, ua)
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
warm := getOnline(t, ts.URL)
|
||||||
|
if warm.Total != 1 || len(warm.Tables) != 1 {
|
||||||
|
t.Fatalf("%+v", warm)
|
||||||
|
}
|
||||||
|
|
||||||
|
clock = baseTime.Add(15 * time.Second)
|
||||||
|
doReq(t, http.MethodGet, ts.URL+"/tiles/building/1/2/3.png", sid, ua)
|
||||||
|
cached := getOnline(t, ts.URL)
|
||||||
|
if cached.ServerTime != warm.ServerTime || len(cached.Tables) != 1 {
|
||||||
|
t.Fatalf("served stale snapshot %+v", cached)
|
||||||
|
}
|
||||||
|
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
fresh := getOnline(t, ts.URL)
|
||||||
|
if len(fresh.Tables) != 2 || fresh.Total != 2 {
|
||||||
|
t.Fatalf("%+v", fresh)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func warmTime(s string) time.Time {
|
||||||
|
tm, err := time.Parse(time.RFC3339, s)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return tm
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChineseTableAndPages(t *testing.T) {
|
||||||
|
app := newTestApp(t, func() time.Time { return time.Date(2026, 9, 23, 10, 0, 0, 0, cst) })
|
||||||
|
ts := httptest.NewServer(app.Handler())
|
||||||
|
t.Cleanup(ts.Close)
|
||||||
|
|
||||||
|
code, hdr, body := doReq(t, http.MethodGet, ts.URL+"/tiles/%E4%B8%9C%E5%8C%BA/12/3/4.png", strings.Repeat("F", 22), "Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2")
|
||||||
|
if code != 200 || hdr.Get("Set-Cookie") != "" {
|
||||||
|
t.Fatalf("chinese tile %d %s", code, hdr.Get("Set-Cookie"))
|
||||||
|
}
|
||||||
|
if !bytes.Equal(body, app.png) {
|
||||||
|
t.Fatal("png mismatch")
|
||||||
|
}
|
||||||
|
flushAndRefresh(t, app)
|
||||||
|
online := getOnline(t, ts.URL)
|
||||||
|
if countsOf(online.Tables)["东区"] != 1 {
|
||||||
|
t.Fatalf("%+v", online)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err := http.Get(ts.URL + "/healthz")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, _ := io.ReadAll(res.Body)
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != 200 || string(b) != "ok" {
|
||||||
|
t.Fatalf("health %d %q", res.StatusCode, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err = http.Get(ts.URL + "/")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, _ = io.ReadAll(res.Body)
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != 200 {
|
||||||
|
t.Fatal(res.StatusCode)
|
||||||
|
}
|
||||||
|
if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" {
|
||||||
|
t.Fatalf("content-type %s", ct)
|
||||||
|
}
|
||||||
|
if res.Header.Get("Cache-Control") != "no-cache" {
|
||||||
|
t.Fatal(res.Header.Get("Cache-Control"))
|
||||||
|
}
|
||||||
|
html := string(b)
|
||||||
|
for _, needle := range []string{
|
||||||
|
"总在线连接",
|
||||||
|
"cards",
|
||||||
|
"overflow: auto",
|
||||||
|
"datetime-local",
|
||||||
|
"queryRange();",
|
||||||
|
"1 小时",
|
||||||
|
"24 小时",
|
||||||
|
"3 天",
|
||||||
|
"visibilitychange",
|
||||||
|
"document.hidden",
|
||||||
|
"textContent",
|
||||||
|
"30000",
|
||||||
|
"encodeURIComponent",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(html, needle) {
|
||||||
|
t.Fatalf("page missing %s", needle)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(html, "innerHTML") {
|
||||||
|
t.Fatal("page uses innerHTML")
|
||||||
|
}
|
||||||
|
if strings.Contains(html, "复制") {
|
||||||
|
t.Fatal("page still has copy button")
|
||||||
|
}
|
||||||
|
|
||||||
|
res, err = http.Get(ts.URL + "/no-such")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != 404 {
|
||||||
|
t.Fatalf("unknown %d", res.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatsUnavailable(t *testing.T) {
|
||||||
|
app := newTestApp(t, time.Now)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||||
|
app.Handler().ServeHTTP(rr, req)
|
||||||
|
if rr.Code != 200 || rr.Body.String() != "ok" {
|
||||||
|
t.Fatalf("health before close %d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
if err := app.store.db.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rr = httptest.NewRecorder()
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||||
|
app.Handler().ServeHTTP(rr, req)
|
||||||
|
if rr.Code != 200 || rr.Body.String() != "ok" {
|
||||||
|
t.Fatalf("health after close %d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
rr = httptest.NewRecorder()
|
||||||
|
req = httptest.NewRequest(http.MethodGet, "/api/online", nil)
|
||||||
|
app.Handler().ServeHTTP(rr, req)
|
||||||
|
if rr.Code != 503 {
|
||||||
|
t.Fatalf("online %d %s", rr.Code, rr.Body)
|
||||||
|
}
|
||||||
|
var body errJSON
|
||||||
|
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body.Error != "stats_unavailable" || body.Message != "统计暂时不可用" {
|
||||||
|
t.Fatalf("%+v", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"database/sql"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
_ "modernc.org/sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Store struct {
|
||||||
|
db *sql.DB
|
||||||
|
closeOnce sync.Once
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func OpenStore(dataDir string) (*Store, error) {
|
||||||
|
if err := os.MkdirAll(dataDir, 0o755); err != nil {
|
||||||
|
return nil, fmt.Errorf("创建数据目录: %w", err)
|
||||||
|
}
|
||||||
|
dsn := "file:" + filepath.ToSlash(filepath.Join(dataDir, "xyz.db")) +
|
||||||
|
"?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)"
|
||||||
|
db, err := sql.Open("sqlite", dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("打开数据库: %w", err)
|
||||||
|
}
|
||||||
|
db.SetMaxOpenConns(4)
|
||||||
|
db.SetMaxIdleConns(4)
|
||||||
|
if err := db.Ping(); err != nil {
|
||||||
|
_ = db.Close()
|
||||||
|
return nil, fmt.Errorf("连接数据库: %w", err)
|
||||||
|
}
|
||||||
|
schema := []string{
|
||||||
|
`CREATE TABLE IF NOT EXISTS meta (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
) WITHOUT ROWID`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS hits (
|
||||||
|
minute INTEGER NOT NULL,
|
||||||
|
tbl TEXT NOT NULL,
|
||||||
|
sid TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (minute, tbl, sid)
|
||||||
|
) WITHOUT ROWID`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
sid TEXT PRIMARY KEY,
|
||||||
|
fp TEXT NOT NULL,
|
||||||
|
first_min INTEGER NOT NULL,
|
||||||
|
last_min INTEGER NOT NULL
|
||||||
|
) WITHOUT ROWID`,
|
||||||
|
`CREATE INDEX IF NOT EXISTS sessions_last_min ON sessions(last_min)`,
|
||||||
|
}
|
||||||
|
for _, q := range schema {
|
||||||
|
if _, err := db.Exec(q); err != nil {
|
||||||
|
_ = db.Close()
|
||||||
|
return nil, fmt.Errorf("建表: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &Store{db: db}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Close() error {
|
||||||
|
s.closeOnce.Do(func() {
|
||||||
|
s.closeErr = s.db.Close()
|
||||||
|
})
|
||||||
|
return s.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Salt(ctx context.Context) ([]byte, error) {
|
||||||
|
var v string
|
||||||
|
err := s.db.QueryRowContext(ctx, `SELECT value FROM meta WHERE key = ?`, "fp_salt").Scan(&v)
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
raw := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v = hex.EncodeToString(raw)
|
||||||
|
if _, err := s.db.ExecContext(ctx, `INSERT INTO meta(key, value) VALUES (?, ?)`, "fp_salt", v); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return raw, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
raw, err := hex.DecodeString(v)
|
||||||
|
if err != nil || len(raw) != 32 {
|
||||||
|
return nil, fmt.Errorf("fp_salt 无效")
|
||||||
|
}
|
||||||
|
return raw, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) WriteBatch(ctx context.Context, hits []hitKey, sessions map[string]*sessionAgg) (int, error) {
|
||||||
|
if len(hits) == 0 && len(sessions) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
tx, err := s.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
insHit, err := tx.PrepareContext(ctx, `INSERT OR IGNORE INTO hits(minute, tbl, sid) VALUES (?, ?, ?)`)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer insHit.Close()
|
||||||
|
|
||||||
|
insSess, err := tx.PrepareContext(ctx, `INSERT INTO sessions(sid, fp, first_min, last_min) VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT(sid) DO UPDATE SET
|
||||||
|
first_min = MIN(first_min, excluded.first_min),
|
||||||
|
last_min = MAX(last_min, excluded.last_min)`)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer insSess.Close()
|
||||||
|
|
||||||
|
for _, h := range hits {
|
||||||
|
if _, err := insHit.ExecContext(ctx, h.minute, h.table, h.sid); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for sid, sess := range sessions {
|
||||||
|
if _, err := insSess.ExecContext(ctx, sid, sess.fp, sess.first, sess.last); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(hits), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Query(ctx context.Context, fromMin, toMin int64) ([]sessionRow, error) {
|
||||||
|
rows, err := s.db.QueryContext(ctx, `
|
||||||
|
SELECT h.tbl, s.sid, s.fp, s.first_min, s.last_min
|
||||||
|
FROM (SELECT DISTINCT tbl, sid FROM hits WHERE minute BETWEEN ? AND ?) AS h
|
||||||
|
JOIN sessions AS s ON s.sid = h.sid`, fromMin, toMin)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []sessionRow
|
||||||
|
for rows.Next() {
|
||||||
|
var row sessionRow
|
||||||
|
if err := rows.Scan(&row.table, &row.sid, &row.fp, &row.first, &row.last); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, row)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Cleanup(ctx context.Context, cutoff int64) error {
|
||||||
|
tx, err := s.db.BeginTx(ctx, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
if _, err := tx.ExecContext(ctx, `DELETE FROM hits WHERE minute < ?`, cutoff); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `DELETE FROM sessions WHERE last_min < ?`, cutoff); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tx.ExecContext(ctx, `UPDATE sessions SET first_min = ? WHERE first_min < ?`, cutoff, cutoff); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Commit()
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStoreUpsertAndSchema(t *testing.T) {
|
||||||
|
st, err := OpenStore(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = st.Close() })
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
var mode, syncMode string
|
||||||
|
var busy int
|
||||||
|
if err := st.db.QueryRow(`PRAGMA journal_mode`).Scan(&mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.EqualFold(mode, "wal") {
|
||||||
|
t.Fatalf("journal_mode %s", mode)
|
||||||
|
}
|
||||||
|
if err := st.db.QueryRow(`PRAGMA synchronous`).Scan(&syncMode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if syncMode != "1" && !strings.EqualFold(syncMode, "NORMAL") {
|
||||||
|
t.Fatalf("synchronous %s", syncMode)
|
||||||
|
}
|
||||||
|
if err := st.db.QueryRow(`PRAGMA busy_timeout`).Scan(&busy); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if busy != 5000 {
|
||||||
|
t.Fatalf("busy_timeout %d", busy)
|
||||||
|
}
|
||||||
|
|
||||||
|
wantCols := map[string]string{
|
||||||
|
"meta": "key,value",
|
||||||
|
"hits": "minute,tbl,sid",
|
||||||
|
"sessions": "sid,fp,first_min,last_min",
|
||||||
|
}
|
||||||
|
for table, want := range wantCols {
|
||||||
|
rows, err := st.db.Query(`SELECT name FROM pragma_table_info('` + table + `') ORDER BY cid`)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var names []string
|
||||||
|
for rows.Next() {
|
||||||
|
var name string
|
||||||
|
if err := rows.Scan(&name); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
rows.Close()
|
||||||
|
if strings.Join(names, ",") != want {
|
||||||
|
t.Fatalf("%s columns %v", table, names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
write := func(fp string, first, last, minute int64) {
|
||||||
|
t.Helper()
|
||||||
|
_, err := st.WriteBatch(ctx, []hitKey{{minute: minute, table: "grid", sid: "A"}}, map[string]*sessionAgg{
|
||||||
|
"A": {fp: fp, first: first, last: last},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write("fp1", 10, 20, 10)
|
||||||
|
write("fp2", 5, 30, 12)
|
||||||
|
if _, err := st.WriteBatch(ctx, nil, map[string]*sessionAgg{
|
||||||
|
"A": {fp: "fp3", first: 8, last: 25},
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var fp string
|
||||||
|
var first, last int64
|
||||||
|
if err := st.db.QueryRow(`SELECT fp, first_min, last_min FROM sessions WHERE sid = ?`, "A").Scan(&fp, &first, &last); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fp != "fp1" || first != 5 || last != 30 {
|
||||||
|
t.Fatalf("fp=%s first=%d last=%d", fp, first, last)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStoreSaltStable(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
ctx := context.Background()
|
||||||
|
s1, err := OpenStore(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
salt1, err := s1.Salt(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(salt1) != 32 {
|
||||||
|
t.Fatalf("salt len %d", len(salt1))
|
||||||
|
}
|
||||||
|
if err := s1.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s2, err := OpenStore(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer s2.Close()
|
||||||
|
salt2, err := s2.Salt(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(salt1) != string(salt2) {
|
||||||
|
t.Fatal("salt changed after reopen")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStoreCleanup(t *testing.T) {
|
||||||
|
st, err := OpenStore(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = st.Close() })
|
||||||
|
ctx := context.Background()
|
||||||
|
const nowMin = int64(1_000_000)
|
||||||
|
cutoff := nowMin - 72*60
|
||||||
|
|
||||||
|
_, err = st.WriteBatch(ctx, []hitKey{
|
||||||
|
{minute: cutoff - 1, table: "grid", sid: "old"},
|
||||||
|
{minute: cutoff, table: "grid", sid: "keep"},
|
||||||
|
{minute: cutoff + 10, table: "grid", sid: "fresh"},
|
||||||
|
}, map[string]*sessionAgg{
|
||||||
|
"old": {fp: "f", first: cutoff - 10, last: cutoff - 1},
|
||||||
|
"keep": {fp: "f", first: cutoff - 10, last: cutoff},
|
||||||
|
"fresh": {fp: "f", first: cutoff + 1, last: cutoff + 10},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := st.Cleanup(ctx, cutoff); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
if err := st.db.QueryRow(`SELECT COUNT(*) FROM hits WHERE minute < ?`, cutoff).Scan(&n); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n != 0 {
|
||||||
|
t.Fatalf("old hits %d", n)
|
||||||
|
}
|
||||||
|
if err := st.db.QueryRow(`SELECT COUNT(*) FROM sessions WHERE last_min < ?`, cutoff).Scan(&n); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n != 0 {
|
||||||
|
t.Fatalf("old sessions %d", n)
|
||||||
|
}
|
||||||
|
var first int64
|
||||||
|
if err := st.db.QueryRow(`SELECT first_min FROM sessions WHERE sid = ?`, "keep").Scan(&first); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if first != cutoff {
|
||||||
|
t.Fatalf("first_min %d", first)
|
||||||
|
}
|
||||||
|
if err := st.db.QueryRow(`SELECT COUNT(*) FROM hits WHERE minute >= ?`, cutoff).Scan(&n); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n != 2 {
|
||||||
|
t.Fatalf("kept hits %d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
type tileRef struct {
|
||||||
|
table string
|
||||||
|
z, x, y string
|
||||||
|
}
|
||||||
|
|
||||||
|
func transparentPNG() []byte {
|
||||||
|
img := image.NewPaletted(image.Rect(0, 0, 256, 256), color.Palette{color.NRGBA{}})
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := png.Encoder{CompressionLevel: png.BestCompression}
|
||||||
|
if err := enc.Encode(&buf, img); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func clientIP(r *http.Request, trustProxy bool) string {
|
||||||
|
var ip net.IP
|
||||||
|
if trustProxy {
|
||||||
|
ip = net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP")))
|
||||||
|
}
|
||||||
|
if ip == nil {
|
||||||
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||||
|
if err != nil {
|
||||||
|
host = r.RemoteAddr
|
||||||
|
}
|
||||||
|
ip = net.ParseIP(host)
|
||||||
|
}
|
||||||
|
if ip == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if v4 := ip.To4(); v4 != nil {
|
||||||
|
return v4.String()
|
||||||
|
}
|
||||||
|
return ip.Mask(net.CIDRMask(64, 128)).String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func fingerprint(salt []byte, ip, ua string) string {
|
||||||
|
if len(ua) > uaMaxBytes {
|
||||||
|
ua = ua[:uaMaxBytes]
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, salt)
|
||||||
|
_, _ = mac.Write([]byte(ip))
|
||||||
|
_, _ = mac.Write([]byte("\n"))
|
||||||
|
_, _ = mac.Write([]byte(ua))
|
||||||
|
sum := mac.Sum(nil)
|
||||||
|
return hex.EncodeToString(sum[:8])
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSID(s string) bool {
|
||||||
|
if len(s) != 22 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
c := s[i]
|
||||||
|
switch {
|
||||||
|
case c >= 'A' && c <= 'Z':
|
||||||
|
case c >= 'a' && c <= 'z':
|
||||||
|
case c >= '0' && c <= '9':
|
||||||
|
case c == '-', c == '_':
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSID() (string, error) {
|
||||||
|
buf := make([]byte, 16)
|
||||||
|
if _, err := rand.Read(buf); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(buf), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validTable(s string) bool {
|
||||||
|
if !utf8.ValidString(s) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
n := utf8.RuneCountInString(s)
|
||||||
|
if n < 1 || n > 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range s {
|
||||||
|
if r == '_' || r == '-' || unicode.IsLetter(r) || unicode.IsDigit(r) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseDigits(s string) (int64, bool) {
|
||||||
|
if len(s) < 1 || len(s) > 10 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
var n int64
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
c := s[i]
|
||||||
|
if c < '0' || c > '9' {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
n = n*10 + int64(c-'0')
|
||||||
|
}
|
||||||
|
return n, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseTilePath(escaped string) (tileRef, bool) {
|
||||||
|
parts := strings.Split(escaped, "/")
|
||||||
|
if len(parts) != 6 || parts[0] != "" || parts[1] != "tiles" {
|
||||||
|
return tileRef{}, false
|
||||||
|
}
|
||||||
|
table, err := url.PathUnescape(parts[2])
|
||||||
|
if err != nil || !validTable(table) {
|
||||||
|
return tileRef{}, false
|
||||||
|
}
|
||||||
|
z, ok := parseDigits(parts[3])
|
||||||
|
if !ok || z > 30 {
|
||||||
|
return tileRef{}, false
|
||||||
|
}
|
||||||
|
if _, ok := parseDigits(parts[4]); !ok {
|
||||||
|
return tileRef{}, false
|
||||||
|
}
|
||||||
|
y, ok := parseY(parts[5])
|
||||||
|
if !ok {
|
||||||
|
return tileRef{}, false
|
||||||
|
}
|
||||||
|
return tileRef{table: table, z: parts[3], x: parts[4], y: y}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseY(seg string) (string, bool) {
|
||||||
|
if !strings.HasSuffix(seg, ".png") {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
num := strings.TrimSuffix(seg, ".png")
|
||||||
|
if _, ok := parseDigits(num); !ok {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return num, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// countedClient 判断请求是否来自 QGIS / QField。QGIS 的网络库总会在 User-Agent 里带上 "QGIS/版本号"。
|
||||||
|
func countedClient(ua string) bool {
|
||||||
|
return strings.Contains(ua, "QGIS/") || strings.Contains(strings.ToLower(ua), "qfield")
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestIsHTTPS(r *http.Request, trustProxy bool) bool {
|
||||||
|
if r.TLS != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return trustProxy && strings.EqualFold(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")), "https")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) shouldCount(r *http.Request) bool {
|
||||||
|
if r.Method != http.MethodGet || !countedClient(r.UserAgent()) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return !a.cfg.HTTPSOnly || requestIsHTTPS(r, a.cfg.TrustProxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func prefix6(s string) string {
|
||||||
|
if len(s) <= 6 {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s[:6]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) handleTile(w http.ResponseWriter, r *http.Request) {
|
||||||
|
tp, ok := parseTilePath(r.URL.EscapedPath())
|
||||||
|
if !ok {
|
||||||
|
a.notFound.Add(1)
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hadSID := ""
|
||||||
|
if c, err := r.Cookie("sid"); err == nil && validSID(c.Value) {
|
||||||
|
hadSID = c.Value
|
||||||
|
}
|
||||||
|
issued := ""
|
||||||
|
if hadSID == "" {
|
||||||
|
id, err := newSID()
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("生成会话失败", "err", err)
|
||||||
|
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
issued = id
|
||||||
|
http.SetCookie(w, &http.Cookie{
|
||||||
|
Name: "sid",
|
||||||
|
Value: issued,
|
||||||
|
Path: "/tiles/",
|
||||||
|
MaxAge: cookieMaxAge,
|
||||||
|
HttpOnly: true,
|
||||||
|
})
|
||||||
|
a.newCookies.Add(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
h := w.Header()
|
||||||
|
h.Set("Content-Type", "image/png")
|
||||||
|
h.Set("Content-Length", strconv.Itoa(len(a.png)))
|
||||||
|
h.Set("Cache-Control", "no-store")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write(a.png)
|
||||||
|
|
||||||
|
counted := a.shouldCount(r)
|
||||||
|
if a.cfg.DebugLog {
|
||||||
|
shown := hadSID
|
||||||
|
if shown == "" {
|
||||||
|
shown = issued
|
||||||
|
}
|
||||||
|
slog.Info("瓦片",
|
||||||
|
"time", a.now().In(cst).Format(timeRFC3339),
|
||||||
|
"table", tp.table,
|
||||||
|
"z", tp.z,
|
||||||
|
"x", tp.x,
|
||||||
|
"y", tp.y,
|
||||||
|
"has_cookie", hadSID != "",
|
||||||
|
"sid", prefix6(shown),
|
||||||
|
"set_cookie", issued != "",
|
||||||
|
"counted", counted,
|
||||||
|
"ip", clientIP(r, a.cfg.TrustProxy),
|
||||||
|
"ua", r.UserAgent(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.tiles.Add(1)
|
||||||
|
if !counted {
|
||||||
|
a.ignored.Add(1)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ip := clientIP(r, a.cfg.TrustProxy)
|
||||||
|
fp := fingerprint(a.salt, ip, r.UserAgent())
|
||||||
|
a.rec.Record(a.now(), tp.table, hadSID, fp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"image/png"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCountedClient(t *testing.T) {
|
||||||
|
ok := []string{
|
||||||
|
"Mozilla/5.0 QGIS/40202/Windows 10 Version 22H2",
|
||||||
|
"Mozilla/5.0 QGIS/33801/Ubuntu 22.04.4 LTS",
|
||||||
|
"QField/3.4.0 QGIS/33400/Android 14",
|
||||||
|
"Mozilla/5.0 qfield/4.2.0",
|
||||||
|
}
|
||||||
|
for _, ua := range ok {
|
||||||
|
if !countedClient(ua) {
|
||||||
|
t.Fatalf("should count %q", ua)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bad := []string{
|
||||||
|
"",
|
||||||
|
"curl/8.13.0",
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/99.0.4844.51 Safari/537.36",
|
||||||
|
"QGIS Desktop",
|
||||||
|
}
|
||||||
|
for _, ua := range bad {
|
||||||
|
if countedClient(ua) {
|
||||||
|
t.Fatalf("should ignore %q", ua)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseTilePath(t *testing.T) {
|
||||||
|
p, ok := parseTilePath("/tiles/%E4%B8%9C%E5%8C%BA/12/3/4.png")
|
||||||
|
if !ok || p.table != "东区" || p.z != "12" || p.x != "3" || p.y != "4" {
|
||||||
|
t.Fatalf("chinese path: %+v ok=%v", p, ok)
|
||||||
|
}
|
||||||
|
if _, ok := parseTilePath("/tiles/" + strings.Repeat("a", 64) + "/1/2/3.png"); !ok {
|
||||||
|
t.Fatal("64 chars should pass")
|
||||||
|
}
|
||||||
|
if _, ok := parseTilePath("/tiles/grid/30/0/0.png"); !ok {
|
||||||
|
t.Fatal("z=30 should pass")
|
||||||
|
}
|
||||||
|
if _, ok := parseTilePath("/tiles/grid/0/0/0.png"); !ok {
|
||||||
|
t.Fatal("zeros should pass")
|
||||||
|
}
|
||||||
|
bad := []string{
|
||||||
|
"/tiles//1/2/3.png",
|
||||||
|
"/tiles/" + strings.Repeat("b", 65) + "/1/2/3.png",
|
||||||
|
"/tiles/a%20b/1/2/3.png",
|
||||||
|
"/tiles/%2F/1/2/3.png",
|
||||||
|
"/tiles/../1/2/3.png",
|
||||||
|
"/tiles/%2E%2E/1/2/3.png",
|
||||||
|
"/tiles/grid/31/1/2.png",
|
||||||
|
"/tiles/grid/1/2/3.PNG",
|
||||||
|
"/tiles/grid/1/2/3.jpg",
|
||||||
|
"/tiles/grid/1/2/.png",
|
||||||
|
"/tiles/grid/1/2/3.png/extra",
|
||||||
|
"/tiles/grid/1/2.png",
|
||||||
|
"/tiles/grid/x/1/2.png",
|
||||||
|
"/tiles/has space/1/2/3.png",
|
||||||
|
"/nope/grid/1/2/3.png",
|
||||||
|
}
|
||||||
|
for _, path := range bad {
|
||||||
|
if _, ok := parseTilePath(path); ok {
|
||||||
|
t.Fatalf("accepted %s", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidSID(t *testing.T) {
|
||||||
|
if !validSID(strings.Repeat("A", 22)) {
|
||||||
|
t.Fatal("22 letters")
|
||||||
|
}
|
||||||
|
if !validSID("abcdefghijklmnopqrstuv") {
|
||||||
|
t.Fatal("22 mixed")
|
||||||
|
}
|
||||||
|
if !validSID("0123456789-_ABCDEFGHIJ") {
|
||||||
|
t.Fatal("charset")
|
||||||
|
}
|
||||||
|
if validSID(strings.Repeat("A", 21)) {
|
||||||
|
t.Fatal("21 should fail")
|
||||||
|
}
|
||||||
|
if validSID(strings.Repeat("A", 21) + "+") {
|
||||||
|
t.Fatal("plus should fail")
|
||||||
|
}
|
||||||
|
if validSID(strings.Repeat("A", 21) + "/") {
|
||||||
|
t.Fatal("slash should fail")
|
||||||
|
}
|
||||||
|
id, err := newSID()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(id) != 22 || !validSID(id) {
|
||||||
|
t.Fatalf("new sid %q", id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFingerprintAndClientIP(t *testing.T) {
|
||||||
|
salt := bytes.Repeat([]byte{7}, 32)
|
||||||
|
ua := "Mozilla/5.0 QGIS/33801/Windows"
|
||||||
|
fp := fingerprint(salt, "203.0.113.5", ua)
|
||||||
|
if len(fp) != 16 {
|
||||||
|
t.Fatalf("fingerprint length %d", len(fp))
|
||||||
|
}
|
||||||
|
if fp != fingerprint(salt, "203.0.113.5", ua) {
|
||||||
|
t.Fatal("same input differs")
|
||||||
|
}
|
||||||
|
if fingerprint(salt, "203.0.113.5", ua) == fingerprint(salt, "203.0.113.6", ua) {
|
||||||
|
t.Fatal("ip should change fingerprint")
|
||||||
|
}
|
||||||
|
long := strings.Repeat("a", 256)
|
||||||
|
if fingerprint(salt, "1.1.1.1", long) != fingerprint(salt, "1.1.1.1", long+"MORE") {
|
||||||
|
t.Fatal("ua over 256 bytes was not truncated")
|
||||||
|
}
|
||||||
|
alt := strings.Repeat("a", 255) + "b"
|
||||||
|
if fingerprint(salt, "1.1.1.1", long) == fingerprint(salt, "1.1.1.1", alt) {
|
||||||
|
t.Fatal("byte 256 should matter")
|
||||||
|
}
|
||||||
|
|
||||||
|
r1 := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r1.RemoteAddr = "[2001:db8:1:2::1]:100"
|
||||||
|
r2 := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r2.RemoteAddr = "[2001:db8:1:2::abcd]:200"
|
||||||
|
ip1 := clientIP(r1, false)
|
||||||
|
ip2 := clientIP(r2, false)
|
||||||
|
if ip1 != ip2 {
|
||||||
|
t.Fatalf("same /64: %s vs %s", ip1, ip2)
|
||||||
|
}
|
||||||
|
if fingerprint(salt, ip1, ua) != fingerprint(salt, ip2, ua) {
|
||||||
|
t.Fatal("same /64 fingerprint differs")
|
||||||
|
}
|
||||||
|
r3 := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r3.RemoteAddr = "[2001:db8:1:3::1]:100"
|
||||||
|
if clientIP(r3, false) == ip1 {
|
||||||
|
t.Fatal("different /64 should differ")
|
||||||
|
}
|
||||||
|
|
||||||
|
r := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
r.RemoteAddr = "192.0.2.10:1234"
|
||||||
|
r.Header.Set("X-Real-IP", "198.51.100.7")
|
||||||
|
if got := clientIP(r, false); got != "192.0.2.10" {
|
||||||
|
t.Fatalf("ignore proxy: %s", got)
|
||||||
|
}
|
||||||
|
if got := clientIP(r, true); got != "198.51.100.7" {
|
||||||
|
t.Fatalf("trust proxy: %s", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
mapped := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
mapped.RemoteAddr = "[::ffff:192.0.2.8]:9"
|
||||||
|
if got := clientIP(mapped, false); got != "192.0.2.8" {
|
||||||
|
t.Fatalf("v4-mapped: %s", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
v6a := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
v6a.RemoteAddr = "192.0.2.1:1"
|
||||||
|
v6a.Header.Set("X-Real-IP", "2001:db8:9:9::1")
|
||||||
|
v6b := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
v6b.RemoteAddr = "192.0.2.1:1"
|
||||||
|
v6b.Header.Set("X-Real-IP", "2001:db8:9:9::ffff")
|
||||||
|
if clientIP(v6a, true) != clientIP(v6b, true) {
|
||||||
|
t.Fatalf("trusted ipv6 /64: %s %s", clientIP(v6a, true), clientIP(v6b, true))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTransparentPNG(t *testing.T) {
|
||||||
|
raw := transparentPNG()
|
||||||
|
if len(raw) == 0 || len(raw) > 200 {
|
||||||
|
t.Fatalf("size %d", len(raw))
|
||||||
|
}
|
||||||
|
img, err := png.Decode(bytes.NewReader(raw))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b := img.Bounds()
|
||||||
|
if b.Dx() != 256 || b.Dy() != 256 {
|
||||||
|
t.Fatalf("bounds %v", b)
|
||||||
|
}
|
||||||
|
for y := b.Min.Y; y < b.Max.Y; y++ {
|
||||||
|
for x := b.Min.X; x < b.Max.X; x++ {
|
||||||
|
_, _, _, a := img.At(x, y).RGBA()
|
||||||
|
if a != 0 {
|
||||||
|
t.Fatalf("pixel %d,%d alpha %d", x, y, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !bytes.Equal(raw, transparentPNG()) {
|
||||||
|
t.Fatal("png not stable")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>图层使用统计</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light; }
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body { height: 100%; overflow: hidden; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font: 14px/1.45 "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||||
|
color: #1a1d21;
|
||||||
|
background: #eef1f4;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
height: 100%;
|
||||||
|
max-width: 1080px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
h1 { margin: 0 0 16px; font-size: 20px; font-weight: 650; flex: none; }
|
||||||
|
.cards {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
section {
|
||||||
|
min-height: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 18px 20px 12px;
|
||||||
|
box-shadow: 0 1px 2px rgba(16, 24, 40, .05), 0 0 0 1px rgba(16, 24, 40, .04);
|
||||||
|
}
|
||||||
|
.list {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: auto;
|
||||||
|
overscroll-behavior: contain;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #667085;
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.hero { display: flex; align-items: baseline; gap: 8px; margin: 0 0 12px; flex: none; }
|
||||||
|
.hero strong { font-size: 40px; line-height: 1; font-weight: 650; letter-spacing: -1px; }
|
||||||
|
.hero span { color: #667085; font-size: 13px; }
|
||||||
|
.empty { color: #98a2b3; margin: 10px 0 0; }
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
th { text-align: left; font-size: 12px; font-weight: 600; color: #98a2b3; padding: 0 0 8px; border-bottom: 1px solid #eef0f3; position: sticky; top: 0; background: #fff; }
|
||||||
|
td { padding: 10px 0; border-bottom: 1px solid #f4f5f7; vertical-align: middle; }
|
||||||
|
tr:last-child td { border-bottom: 0; }
|
||||||
|
td.name { font-weight: 600; }
|
||||||
|
td.num { width: 56px; font-variant-numeric: tabular-nums; }
|
||||||
|
.filters { display: flex; flex-wrap: wrap; align-items: end; gap: 8px 10px; margin-bottom: 10px; flex: none; }
|
||||||
|
label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: #667085; }
|
||||||
|
input[type="datetime-local"] {
|
||||||
|
font: inherit;
|
||||||
|
color: #1a1d21;
|
||||||
|
width: 188px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border: 1px solid #d0d5dd;
|
||||||
|
border-radius: 7px;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
input:focus { outline: 2px solid #1a1d21; outline-offset: 1px; }
|
||||||
|
.btns { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||||
|
button {
|
||||||
|
font: inherit;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: 7px;
|
||||||
|
border: 1px solid #d0d5dd;
|
||||||
|
background: #fff;
|
||||||
|
color: #1a1d21;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
button:hover { background: #f2f4f7; }
|
||||||
|
button.primary { background: #1a1d21; color: #fff; border-color: #1a1d21; }
|
||||||
|
button.primary:hover { background: #333; }
|
||||||
|
button:disabled { opacity: .45; cursor: default; }
|
||||||
|
.fail { color: #b42318; font-size: 12px; font-weight: 500; flex: none; min-height: 1em; margin: 0 0 6px; }
|
||||||
|
.range-head { flex: none; }
|
||||||
|
.meta { color: #98a2b3; font-size: 12px; margin: 0 0 6px; }
|
||||||
|
.sum { font-size: 15px; font-weight: 650; margin: 0 0 2px; }
|
||||||
|
@media (max-width: 860px) {
|
||||||
|
.cards { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>图层使用统计</h1>
|
||||||
|
<div class="cards">
|
||||||
|
<section>
|
||||||
|
<h2>现在 <span id="fail" class="fail"></span></h2>
|
||||||
|
<p class="hero"><strong id="total">—</strong><span>总在线连接</span></p>
|
||||||
|
<div id="online-list" class="list"></div>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>查历史</h2>
|
||||||
|
<div class="filters">
|
||||||
|
<label>从 <input id="start" type="datetime-local" step="1"></label>
|
||||||
|
<label>到 <input id="end" type="datetime-local" step="1"></label>
|
||||||
|
<div class="btns">
|
||||||
|
<button type="button" id="q1">1 小时</button>
|
||||||
|
<button type="button" id="q24">24 小时</button>
|
||||||
|
<button type="button" id="q72">3 天</button>
|
||||||
|
<button type="button" id="qgo" class="primary">查询</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p id="range-err" class="fail"></p>
|
||||||
|
<div id="range-head" class="range-head"></div>
|
||||||
|
<div id="range-list" class="list"></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var RETAIN = 72 * 60 * 60 * 1000;
|
||||||
|
var SLACK = 5 * 60 * 1000;
|
||||||
|
var startEl = document.getElementById("start");
|
||||||
|
var endEl = document.getElementById("end");
|
||||||
|
var errEl = document.getElementById("range-err");
|
||||||
|
var buttons = [document.getElementById("q1"), document.getElementById("q24"), document.getElementById("q72"), document.getElementById("qgo")];
|
||||||
|
var timer = 0;
|
||||||
|
var offset = 0;
|
||||||
|
var defaulted = false;
|
||||||
|
|
||||||
|
function serverNow() { return Date.now() + offset; }
|
||||||
|
function pad(n) { return String(n).padStart(2, "0"); }
|
||||||
|
function bj(ms) { return new Date(ms + 8 * 3600 * 1000); }
|
||||||
|
|
||||||
|
function toLocal(ms) {
|
||||||
|
var d = bj(ms);
|
||||||
|
return d.getUTCFullYear() + "-" + pad(d.getUTCMonth() + 1) + "-" + pad(d.getUTCDate())
|
||||||
|
+ "T" + pad(d.getUTCHours()) + ":" + pad(d.getUTCMinutes()) + ":" + pad(d.getUTCSeconds());
|
||||||
|
}
|
||||||
|
|
||||||
|
function toShow(ms) {
|
||||||
|
var d = bj(ms);
|
||||||
|
return d.getUTCFullYear() + "/" + pad(d.getUTCMonth() + 1) + "/" + pad(d.getUTCDate())
|
||||||
|
+ " " + pad(d.getUTCHours()) + ":" + pad(d.getUTCMinutes());
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLocal(s) {
|
||||||
|
var m = String(s).match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/);
|
||||||
|
if (!m) return null;
|
||||||
|
return Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] || 0)) - 8 * 3600 * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toRFC(ms) { return toLocal(ms) + "+08:00"; }
|
||||||
|
|
||||||
|
function el(tag, text) {
|
||||||
|
var node = document.createElement(tag);
|
||||||
|
if (text != null) node.textContent = text;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillTable(parent, rows, online) {
|
||||||
|
parent.textContent = "";
|
||||||
|
if (!rows || rows.length === 0) {
|
||||||
|
parent.appendChild(el("p", online ? "现在没有人在用。" : "这段时间没有记录。"));
|
||||||
|
parent.lastChild.className = "empty";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var table = el("table");
|
||||||
|
var hr = el("tr");
|
||||||
|
hr.appendChild(el("th", "图层"));
|
||||||
|
hr.appendChild(el("th", "连接"));
|
||||||
|
var thead = el("thead");
|
||||||
|
thead.appendChild(hr);
|
||||||
|
table.appendChild(thead);
|
||||||
|
var tb = el("tbody");
|
||||||
|
rows.forEach(function (row) {
|
||||||
|
var tr = el("tr");
|
||||||
|
var name = el("td", row.table);
|
||||||
|
name.className = "name";
|
||||||
|
var num = el("td", String(row.count));
|
||||||
|
num.className = "num";
|
||||||
|
tr.appendChild(name);
|
||||||
|
tr.appendChild(num);
|
||||||
|
tb.appendChild(tr);
|
||||||
|
});
|
||||||
|
table.appendChild(tb);
|
||||||
|
parent.appendChild(table);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillDefault() {
|
||||||
|
var end = serverNow();
|
||||||
|
startEl.value = toLocal(end - 60 * 60 * 1000);
|
||||||
|
endEl.value = toLocal(end);
|
||||||
|
var earliest = toLocal(end - RETAIN);
|
||||||
|
var latest = toLocal(end);
|
||||||
|
startEl.min = earliest;
|
||||||
|
startEl.max = latest;
|
||||||
|
endEl.min = earliest;
|
||||||
|
endEl.max = latest;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateRange() {
|
||||||
|
var s = parseLocal(startEl.value);
|
||||||
|
var e = parseLocal(endEl.value);
|
||||||
|
if (s == null || e == null) return "请选择开始和结束时间";
|
||||||
|
if (s >= e) return "开始时间要早于结束时间";
|
||||||
|
if (e - s > RETAIN) return "一次最多查 3 天";
|
||||||
|
var earliest = serverNow() - RETAIN;
|
||||||
|
if (s < earliest && earliest - s > SLACK) return "只能查最近 3 天";
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBusy(busy) {
|
||||||
|
buttons.forEach(function (btn) { btn.disabled = busy; });
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderRange(data) {
|
||||||
|
var head = document.getElementById("range-head");
|
||||||
|
head.textContent = "";
|
||||||
|
head.appendChild(el("p", "总连接 " + data.total));
|
||||||
|
head.lastChild.className = "sum";
|
||||||
|
head.appendChild(el("p", toShow(Date.parse(data.start)) + " – " + toShow(Date.parse(data.end))));
|
||||||
|
head.lastChild.className = "meta";
|
||||||
|
fillTable(document.getElementById("range-list"), data.tables, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
function queryRange() {
|
||||||
|
var msg = validateRange();
|
||||||
|
if (msg) {
|
||||||
|
errEl.textContent = msg;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
errEl.textContent = "";
|
||||||
|
setBusy(true);
|
||||||
|
var url = "/api/range?start=" + encodeURIComponent(toRFC(parseLocal(startEl.value)))
|
||||||
|
+ "&end=" + encodeURIComponent(toRFC(parseLocal(endEl.value)));
|
||||||
|
fetch(url, { cache: "no-store" }).then(function (res) {
|
||||||
|
return res.json().then(function (data) {
|
||||||
|
if (!res.ok) {
|
||||||
|
errEl.textContent = data && data.message ? data.message : "查询失败";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
renderRange(data);
|
||||||
|
});
|
||||||
|
}).catch(function () {
|
||||||
|
errEl.textContent = "查询失败";
|
||||||
|
}).then(function () {
|
||||||
|
setBusy(false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function quick(ms) {
|
||||||
|
var end = serverNow();
|
||||||
|
startEl.value = toLocal(end - ms);
|
||||||
|
endEl.value = toLocal(end);
|
||||||
|
queryRange();
|
||||||
|
}
|
||||||
|
|
||||||
|
function refreshOnline() {
|
||||||
|
if (document.hidden) return Promise.resolve();
|
||||||
|
return fetch("/api/online", { cache: "no-store" }).then(function (res) {
|
||||||
|
if (!res.ok) throw new Error("bad status");
|
||||||
|
return res.json();
|
||||||
|
}).then(function (data) {
|
||||||
|
offset = Date.parse(data.server_time) - Date.now();
|
||||||
|
if (!defaulted) {
|
||||||
|
fillDefault();
|
||||||
|
defaulted = true;
|
||||||
|
queryRange();
|
||||||
|
}
|
||||||
|
document.getElementById("total").textContent = String(data.total);
|
||||||
|
document.getElementById("fail").textContent = "";
|
||||||
|
fillTable(document.getElementById("online-list"), data.tables, true);
|
||||||
|
}).catch(function () {
|
||||||
|
document.getElementById("fail").textContent = "暂时连不上";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function schedule() {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (document.hidden) return;
|
||||||
|
timer = setTimeout(function () {
|
||||||
|
refreshOnline().then(schedule);
|
||||||
|
}, 30000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function tick() {
|
||||||
|
return refreshOnline().then(schedule);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById("q1").addEventListener("click", function () { quick(60 * 60 * 1000); });
|
||||||
|
document.getElementById("q24").addEventListener("click", function () { quick(24 * 60 * 60 * 1000); });
|
||||||
|
document.getElementById("q72").addEventListener("click", function () { quick(72 * 60 * 60 * 1000); });
|
||||||
|
document.getElementById("qgo").addEventListener("click", queryRange);
|
||||||
|
document.addEventListener("visibilitychange", function () {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (!document.hidden) tick();
|
||||||
|
});
|
||||||
|
|
||||||
|
fillDefault();
|
||||||
|
tick();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user