Files
dpl/scripts/project-domains/fuc_navigation_stats.py
T

228 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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()