feat(fuc): report aggregate navigation probe outcomes to TeleHub
This commit is contained in:
1 parent
e35b61b3db
commit
bcdbfcad5a
7 files changed
+299
-3
No files matched your search
@@ -17,4 +17,8 @@ node scripts/project-domains/manage.mjs check fuc
|
||||
|
||||
打开页面或点「重新检测」时,浏览器并行请求五个入口的 `/api/v1/guest/comm/config`,确认是 XB 访客响应后显示耗时。每次请求最多 3 秒,不带登录态和邀请码。成功时优先选中最快的入口,手动选择保留;全部失败保留当前选项。只有点击「立即进入」才跳转,邀请码随注册链接传递。本地预览的测速和注册均使用 xb.loc,用于验证交互和本地请求。
|
||||
|
||||
发布只从指定 Git 提交提取 `public/brand/fuc-navigation/` 下的 `index.html`、`clipboard.mjs`、`logo.svg`,落在 `/var/www/wwwroot/fuc-navigation/releases/<SHA>`,再切换 `current`。静态清单不依赖面板或 DomainHub 在线。导航站的 CSP `connect-src` 只放行五个面板域名及对应 tomtojapan 反代的测速接口。发布时分别核对两个导航域名发起的 CORS 请求,并回读 [导航根域](https://fu-nav3.com/)与已登记的 tomtojapan 反代。异常时将 `current` 指回上一次验收的版本,并恢复上一次导航 CSP。
|
||||
每轮测速结束后,正式导航和反代分别向同源 `POST /_nav-stats` 提交一次五条结果。统计只存按日期、导航来源和域名汇总的成功、超时、其他失败计数。统计量是提交成功的测速轮次,用户在测速结束前离开不计入。北京时间每天 08:00 统计过去 24 小时,并通过 TeleHub 的 `info` 发往 `base`。首期注明开始采集时间。日报正文和回执保存在独立 SQLite,同一天的重试沿用原幂等键。
|
||||
|
||||
采集和日报在 site-jp01 执行。部署从 Git 同步导航资产和统计脚本,使用独立系统服务 `fuc-navigation-stats.service` 和 `fuc-navigation-report.timer`。日报凭据由后者通过 systemd 私有凭据读取。停止统计时先切回上一版导航,再撤销两端的统计入口并停用服务和定时器。保留统计库及已发回执。
|
||||
|
||||
发布只从指定 Git 提交提取 `public/brand/fuc-navigation/` 下的 `index.html`、`clipboard.mjs`、`logo.svg`,落在 `/var/www/wwwroot/fuc-navigation/releases/<SHA>`,再切换 `current`。静态清单不依赖面板或 DomainHub 在线。导航站的 CSP `connect-src` 放行五个面板域名及对应 tomtojapan 反代的测速接口,以及两个导航入口的统计地址。发布时分别核对两个导航域名发起的 CORS 请求,并回读 [导航根域](https://fu-nav3.com/)与已登记的 tomtojapan 反代。异常时将 `current` 指回上一次验收的版本,并恢复上一次导航 CSP。
|
||||
@@ -261,10 +261,12 @@
|
||||
const { data } = await response.json();
|
||||
if (typeof data?.app_name !== 'string') throw new Error('Invalid XB response');
|
||||
const elapsed = performance.now() - started;
|
||||
entry.outcome = 'success';
|
||||
entry.result.textContent = Math.max(1, Math.round(elapsed)) + ' ms';
|
||||
return { entry, elapsed };
|
||||
} catch {
|
||||
entry.result.textContent = controller.signal.aborted ? '超时' : '不可用';
|
||||
entry.outcome = controller.signal.aborted ? 'timeout' : 'failure';
|
||||
entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '不可用';
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
@@ -298,6 +300,13 @@
|
||||
if (!manualSelection) fastest.entry.input.checked = true;
|
||||
}
|
||||
testStatus = fastest ? (isLocal ? '本地测速完成' : '测速完成') : '未测得可用入口';
|
||||
if (!isLocal) {
|
||||
const outcomes = Object.fromEntries(entries.map(({ input, outcome }) => [input.dataset.domainhubCode, outcome]));
|
||||
fetch('/_nav-stats', {
|
||||
method: 'POST', body: JSON.stringify(outcomes), credentials: 'omit',
|
||||
keepalive: true, referrerPolicy: 'no-referrer', redirect: 'error',
|
||||
}).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
recheck.disabled = false;
|
||||
panel.removeAttribute('aria-busy');
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Count browser probe outcomes and deliver the FUC navigation digest."""
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
from datetime import date, datetime, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
ORIGINS = {
|
||||
"https://fu-nav3.com": "正式导航",
|
||||
"https://fu-nav3.tomtojapan.online": "反代导航",
|
||||
}
|
||||
OUTCOMES = ("success", "timeout", "failure")
|
||||
TERMINAL = {"sent", "failed", "uncertain", "cancelled", "rejected"}
|
||||
REPORT_ENDPOINT = "https://telehub.gemcook.net/api/v1/messages"
|
||||
REPORT_ROUTE = "/_nav-stats"
|
||||
|
||||
|
||||
def current_end(now):
|
||||
return (now - timedelta(hours=8)).date() + timedelta(days=1)
|
||||
|
||||
|
||||
def connect(path):
|
||||
db = sqlite3.connect(path, timeout=4)
|
||||
db.row_factory = sqlite3.Row
|
||||
return db
|
||||
|
||||
|
||||
def initialize(db, now):
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS totals (
|
||||
day TEXT NOT NULL, source TEXT NOT NULL, domain TEXT NOT NULL,
|
||||
success INTEGER NOT NULL, timeout INTEGER NOT NULL, failure INTEGER NOT NULL,
|
||||
PRIMARY KEY (day, source, domain)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
day TEXT PRIMARY KEY, text TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
receipt TEXT, retry_at INTEGER NOT NULL DEFAULT 0, error TEXT
|
||||
);
|
||||
""")
|
||||
with db:
|
||||
db.execute("INSERT OR IGNORE INTO metadata VALUES ('started', ?)", (now.isoformat(),))
|
||||
|
||||
|
||||
def count_round(db, catalog, origin, values, now):
|
||||
if origin not in ORIGINS or not isinstance(values, dict) or set(values) != set(catalog):
|
||||
raise ValueError("invalid sample")
|
||||
if any(value not in OUTCOMES for value in values.values()):
|
||||
raise ValueError("invalid outcome")
|
||||
rows = [
|
||||
(str(current_end(now)), origin, domain, *(outcome == status for status in OUTCOMES))
|
||||
for domain, outcome in values.items()
|
||||
]
|
||||
with db:
|
||||
db.executemany("""
|
||||
INSERT INTO totals VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(day, source, domain) DO UPDATE SET
|
||||
success = success + excluded.success,
|
||||
timeout = timeout + excluded.timeout,
|
||||
failure = failure + excluded.failure
|
||||
""", rows)
|
||||
|
||||
|
||||
def format_report(db, catalog, day):
|
||||
started = datetime.fromisoformat(db.execute("SELECT value FROM metadata WHERE key='started'").fetchone()[0])
|
||||
first = day - timedelta(days=1)
|
||||
lines = ["【福云 - 导航测速日报】", f"{first} 08:00 至 {day} 08:00(北京时间)"]
|
||||
if day == current_end(started):
|
||||
lines.append(f"本期从 {started:%m-%d %H:%M} 开始采集")
|
||||
rows = db.execute("SELECT * FROM totals WHERE day = ?", (str(day),))
|
||||
totals = {(row["source"], row["domain"]): row for row in rows}
|
||||
for origin, title in ORIGINS.items():
|
||||
lines.extend(("", title))
|
||||
if not any((origin, key) in totals for key in catalog):
|
||||
lines.append("暂无样本")
|
||||
continue
|
||||
for key, name in catalog.items():
|
||||
row = totals.get((origin, key))
|
||||
counts = [row[value] if row else 0 for value in OUTCOMES]
|
||||
total = sum(counts)
|
||||
if not total:
|
||||
lines.append(f"{name}:暂无样本")
|
||||
continue
|
||||
parts = [f"{label} {count / total:.1%}({count})"
|
||||
for label, count in zip(("成功", "超时", "其他失败"), counts)]
|
||||
lines.append(f"{name}:{total} 次," + ",".join(parts))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def telehub_request(token, report):
|
||||
if not re.fullmatch(r"telehub_[a-f0-9]{64}", token):
|
||||
raise ValueError("invalid TeleHub credential format")
|
||||
headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
|
||||
if report["receipt"]:
|
||||
req = Request(REPORT_ENDPOINT + "/" + report["receipt"], headers=headers)
|
||||
else:
|
||||
headers.update({
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": "fuc.navigation.latency." + report["day"],
|
||||
})
|
||||
body = json.dumps({"bot": "info", "target": "base", "text": report["text"]}, ensure_ascii=False).encode()
|
||||
req = Request(REPORT_ENDPOINT, data=body, headers=headers)
|
||||
with build_opener(NoRedirect()).open(req, timeout=8) as result:
|
||||
return json.load(result)["data"]
|
||||
|
||||
|
||||
def deliver(db, catalog, now, send):
|
||||
started = datetime.fromisoformat(db.execute("SELECT value FROM metadata WHERE key='started'").fetchone()[0])
|
||||
day = current_end(started)
|
||||
latest = current_end(now) - timedelta(days=1)
|
||||
while day <= latest:
|
||||
if not db.execute("SELECT 1 FROM reports WHERE day=?", (str(day),)).fetchone():
|
||||
with db:
|
||||
db.execute("INSERT INTO reports (day,text) VALUES (?,?)", (str(day), format_report(db, catalog, day)))
|
||||
day += timedelta(days=1)
|
||||
timestamp = int(now.timestamp())
|
||||
reports = db.execute("""
|
||||
SELECT * FROM reports WHERE status IN ('pending','queued','sending') AND retry_at <= ? ORDER BY day LIMIT 4
|
||||
""", (timestamp,)).fetchall()
|
||||
for report in reports:
|
||||
receipt, status, delay, error = report["receipt"], report["status"], 900, None
|
||||
try:
|
||||
response = send(report)
|
||||
if not isinstance(response, dict):
|
||||
raise ValueError("invalid TeleHub response")
|
||||
new_receipt = response.get("id", "")
|
||||
new_status = response.get("status")
|
||||
if (not isinstance(new_receipt, str)
|
||||
or not re.fullmatch(r"[a-f0-9-]{36}", new_receipt)
|
||||
or (receipt and receipt != new_receipt)
|
||||
or new_status not in TERMINAL | {"queued", "sending"}
|
||||
or response.get("bot_code") != "info" or response.get("target_code") != "base"):
|
||||
raise ValueError("invalid TeleHub receipt")
|
||||
receipt, status = new_receipt, new_status
|
||||
except HTTPError as exc:
|
||||
error = "telehub_http_" + str(exc.code)
|
||||
if exc.code == 429:
|
||||
retry = exc.headers.get("Retry-After", "")
|
||||
if retry.isdigit():
|
||||
delay = max(delay, int(retry))
|
||||
elif 400 <= exc.code < 500:
|
||||
status = "rejected"
|
||||
except (ValueError, KeyError, OSError, URLError):
|
||||
error = "telehub_transport_or_response"
|
||||
with db:
|
||||
db.execute("UPDATE reports SET receipt=?, status=?, retry_at=?, error=? WHERE day=?",
|
||||
(receipt, status, timestamp + delay, error, report["day"]))
|
||||
print(report["day"], status, receipt or "-", error or "-", flush=True)
|
||||
|
||||
|
||||
def serve(path, catalog, port):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
timeout = 4
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != REPORT_ROUTE:
|
||||
self.send_error(404)
|
||||
return
|
||||
try:
|
||||
origin = self.headers.get("Origin")
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if origin not in ORIGINS or not 1 <= length <= 1024:
|
||||
raise ValueError("invalid request")
|
||||
values = json.loads(self.rfile.read(length))
|
||||
with closing(connect(path)) as db:
|
||||
count_round(db, catalog, origin, values, datetime.now(SHANGHAI))
|
||||
except (ValueError, OSError, RecursionError):
|
||||
self.send_error(400)
|
||||
return
|
||||
except sqlite3.Error:
|
||||
self.send_error(503)
|
||||
return
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--database", type=Path, required=True)
|
||||
parser.add_argument("--catalog", type=Path, required=True)
|
||||
sub = parser.add_subparsers(dest="mode", required=True)
|
||||
sub.add_parser("serve").add_argument("--port", type=int, default=18248)
|
||||
sub.add_parser("report")
|
||||
sub.add_parser("preview").add_argument("day", type=date.fromisoformat)
|
||||
args = parser.parse_args()
|
||||
catalog = {item["domainhub"]: item["domain"] for item in json.loads(args.catalog.read_text())["domains"]
|
||||
if item["role"] in {"primary", "direct"}}
|
||||
now = datetime.now(SHANGHAI)
|
||||
with closing(connect(args.database)) as db:
|
||||
initialize(db, now)
|
||||
if args.mode == "preview":
|
||||
print(format_report(db, catalog, args.day))
|
||||
elif args.mode == "report":
|
||||
credential = Path(os.environ["CREDENTIALS_DIRECTORY"])/"telehub-token"
|
||||
token = credential.read_text().strip()
|
||||
with args.database.with_suffix(".report.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
deliver(db, catalog, now, lambda report: telehub_request(token, report))
|
||||
if args.mode == "serve":
|
||||
serve(args.database, catalog, args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=FUC navigation daily TeleHub report
|
||||
After=network-online.target fuc-navigation-stats.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=fuc-nav-stats
|
||||
Group=fuc-nav-stats
|
||||
StateDirectory=fuc-navigation-stats
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
LoadCredential=telehub-token:/etc/fuc-navigation-stats/telehub-token
|
||||
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/fuc_navigation_stats.py --catalog /var/www/wwwroot/fuc-navigation/current/ops/fuc.json --database /var/lib/fuc-navigation-stats/counters.sqlite3 report
|
||||
TimeoutStartSec=55
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=FUC navigation daily report and receipt checks
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* *:00/15:00 Asia/Shanghai
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=FUC navigation probe counters
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=fuc-nav-stats
|
||||
Group=fuc-nav-stats
|
||||
StateDirectory=fuc-navigation-stats
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/fuc_navigation_stats.py --catalog /var/www/wwwroot/fuc-navigation/current/ops/fuc.json --database /var/lib/fuc-navigation-stats/counters.sqlite3 serve
|
||||
Restart=on-failure
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -260,10 +260,12 @@
|
||||
const { data } = await response.json();
|
||||
if (typeof data?.app_name !== 'string') throw new Error('Invalid XB response');
|
||||
const elapsed = performance.now() - started;
|
||||
entry.outcome = 'success';
|
||||
entry.result.textContent = Math.max(1, Math.round(elapsed)) + ' ms';
|
||||
return { entry, elapsed };
|
||||
} catch {
|
||||
entry.result.textContent = controller.signal.aborted ? '超时' : '不可用';
|
||||
entry.outcome = controller.signal.aborted ? 'timeout' : 'failure';
|
||||
entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '不可用';
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
@@ -297,6 +299,13 @@
|
||||
if (!manualSelection) fastest.entry.input.checked = true;
|
||||
}
|
||||
testStatus = fastest ? (isLocal ? '本地测速完成' : '测速完成') : '未测得可用入口';
|
||||
if (!isLocal) {
|
||||
const outcomes = Object.fromEntries(entries.map(({ input, outcome }) => [input.dataset.domainhubCode, outcome]));
|
||||
fetch('/_nav-stats', {
|
||||
method: 'POST', body: JSON.stringify(outcomes), credentials: 'omit',
|
||||
keepalive: true, referrerPolicy: 'no-referrer', redirect: 'error',
|
||||
}).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
recheck.disabled = false;
|
||||
panel.removeAttribute('aria-busy');
|
||||
|
||||
Reference in new issue
Block a user