feat: 只保留管理入口,缓存小区信息表解析,连接中显示提示,移除脚本管理打包方式
This commit is contained in:
+3
-2
@@ -8,8 +8,6 @@ from dataclasses import asdict, dataclass, field, fields, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
import main
|
||||
|
||||
TIMEZONE = os.getenv("TZ") or "Asia/Shanghai"
|
||||
@@ -122,6 +120,9 @@ def validate(data: dict[str, Any], current: Settings) -> Settings:
|
||||
}
|
||||
settings = Settings(**values)
|
||||
if settings.schedule_mode == "cron":
|
||||
# Imported here so the worker process, which only reads saved settings, does not load the scheduler.
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
try:
|
||||
CronTrigger.from_crontab(settings.cron_expression, timezone=TIMEZONE)
|
||||
except ValueError as exc:
|
||||
|
||||
@@ -342,16 +342,6 @@ class MySqlSummaryStore:
|
||||
raise main.ProcessingError(f"MySQL query failed: {exc}") from exc
|
||||
return [dict(zip(names, record, strict=True)) for record in records]
|
||||
|
||||
def ping(self) -> str:
|
||||
connection = self._open(database=None)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT VERSION()")
|
||||
row = cursor.fetchone()
|
||||
return str(row[0]) if row else ""
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _connection(self) -> Any:
|
||||
if not self._schema_ready:
|
||||
self._ensure_schema()
|
||||
|
||||
+6
-1
@@ -58,7 +58,8 @@ MESSAGES: dict[str, dict[str, str]] = {
|
||||
"trigger.schedule": "定时",
|
||||
"trigger.manual": "手动",
|
||||
"trigger.dryRun": "试运行",
|
||||
"detail.missing": "缺少 {count} 类:{sources}", "detail.noFiles": "未找到源文件",
|
||||
"detail.missing": "缺少 {count} 类:{sources}",
|
||||
"detail.noFiles": "未找到源文件",
|
||||
"detail.upToDate": "数据库已是 {time}",
|
||||
"detail.timeout": "超过 {n} 分钟未完成",
|
||||
"detail.dryRunOutput": "结果保存在本地",
|
||||
@@ -179,6 +180,8 @@ MESSAGES: dict[str, dict[str, str]] = {
|
||||
"error.invalidIdentifier": "“{field}”只能包含字母、数字和下划线",
|
||||
"forbidden.title": "无权访问",
|
||||
"forbidden.body": "只有应用管理员可以打开管理界面。",
|
||||
"connect.title": "正在连接…",
|
||||
"connect.slow": "连接时间比平时长。请检查浏览器代理或网络设置,然后刷新页面。",
|
||||
},
|
||||
"en": {
|
||||
"app.title": "Interference ETL",
|
||||
@@ -358,6 +361,8 @@ MESSAGES: dict[str, dict[str, str]] = {
|
||||
"error.invalidIdentifier": "{field} may only contain letters, digits and underscores",
|
||||
"forbidden.title": "Access denied",
|
||||
"forbidden.body": "Only app administrators can open this page.",
|
||||
"connect.title": "Connecting…",
|
||||
"connect.slow": "This is taking longer than usual. Check the browser proxy or network settings, then refresh the page.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ class Runner:
|
||||
self.data_dir = data_dir
|
||||
self.output_dir = data_dir / "output"
|
||||
self.log_dir = data_dir / "logs"
|
||||
self.cache_dir = data_dir / "cache" / "cell-data"
|
||||
self.command = command or [sys.executable, "-m", "etl_app.worker"]
|
||||
self.seconds_per_minute = 60.0
|
||||
self._lock = threading.Lock()
|
||||
@@ -101,6 +102,17 @@ class Runner:
|
||||
def _finish(self, run_id: int, dry_run: bool) -> None:
|
||||
try:
|
||||
self._execute(run_id, dry_run)
|
||||
except Exception as exc:
|
||||
# A record that never got its result would stay "running" until the next restart.
|
||||
record = self.runs.get(run_id)
|
||||
if record is not None and record["status"] == "running":
|
||||
self.runs.finish(
|
||||
run_id,
|
||||
status="failed",
|
||||
finished_at=now_text(),
|
||||
detail=f"{type(exc).__name__}: {exc}"[:DETAIL_LIMIT],
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
self._process = None
|
||||
self._current = None
|
||||
@@ -125,6 +137,8 @@ class Runner:
|
||||
str(self.settings_store.path),
|
||||
"--output",
|
||||
str(self.output_dir),
|
||||
"--cache",
|
||||
str(self.cache_dir),
|
||||
*(["--dry-run"] if dry_run else []),
|
||||
]
|
||||
env = {key: value for key, value in os.environ.items() if key != "METRIX_APP_PROXY_TOKEN"}
|
||||
|
||||
+4
-9
@@ -7,19 +7,13 @@ from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Body, Depends, FastAPI, HTTPException
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
|
||||
from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse
|
||||
|
||||
from .auth import Identity, require_admin
|
||||
from .config import SettingsError, data_dir, public_view
|
||||
from .data import DataQuery
|
||||
from .service import EtlService
|
||||
|
||||
LANDING_HTML = """<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>干扰数据处理</title>
|
||||
<script>location.replace(location.pathname.replace(/\\/?$/, '/') + 'admin');</script>
|
||||
</head><body><a href="admin">干扰数据处理</a></body></html>
|
||||
"""
|
||||
|
||||
|
||||
def settings_error(exc: SettingsError) -> JSONResponse:
|
||||
return JSONResponse(status_code=422, content={"error": exc.key, "field": exc.field, "params": exc.params})
|
||||
@@ -37,8 +31,9 @@ def build_api(service: EtlService) -> FastAPI:
|
||||
api = FastAPI(title="InterferenceETL", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
@api.get("/", include_in_schema=False)
|
||||
def landing() -> HTMLResponse:
|
||||
return HTMLResponse(LANDING_HTML)
|
||||
def landing() -> RedirectResponse:
|
||||
# Relative on purpose: the app is served under a path prefix it does not know.
|
||||
return RedirectResponse("admin")
|
||||
|
||||
@api.get("/healthz")
|
||||
def health() -> dict[str, bool]:
|
||||
|
||||
@@ -298,6 +298,15 @@ html, body { height: 100%; overflow: hidden; }
|
||||
.etl-check-name { font-weight: 600; flex-shrink: 0; }
|
||||
.etl-check-text { color: var(--etl-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.etl-connecting {
|
||||
flex: 1; width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 12px; padding: 24px; text-align: center; color: var(--etl-muted);
|
||||
}
|
||||
.etl-connecting-spinner { color: var(--etl-primary); }
|
||||
.etl-connecting-title { font-size: 14px; }
|
||||
.etl-connecting-hint { max-width: 440px; font-size: 13px; line-height: 1.6; opacity: 0; animation: etl-reveal 0.3s ease 8s forwards; }
|
||||
@keyframes etl-reveal { to { opacity: 1; } }
|
||||
|
||||
.etl-forbidden { min-height: 100vh; width: 100%; display: grid; place-items: center; }
|
||||
.etl-forbidden-card { padding: 40px 56px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; }
|
||||
.etl-forbidden-icon { font-size: 40px; color: var(--etl-muted); }
|
||||
|
||||
+22
-3
@@ -50,12 +50,23 @@ def register(service: EtlService) -> None:
|
||||
async def admin_page(request: Request, client: Client) -> None:
|
||||
ui.add_head_html(STYLE)
|
||||
identity = identify(request.headers)
|
||||
accept = request.headers.get("accept-language", "").lower()
|
||||
fallback = Translator("en" if accept.startswith("en") else "zh")
|
||||
if identity is None or not identity.is_admin:
|
||||
accept = request.headers.get("accept-language", "").lower()
|
||||
render_forbidden(Translator("en" if accept.startswith("en") else "zh"))
|
||||
render_forbidden(fallback)
|
||||
return
|
||||
# The page is built over the live connection. Until it is up, show that instead of an empty page.
|
||||
connecting = render_connecting(fallback)
|
||||
await client.connected()
|
||||
prefs = await ui.run_javascript(PREFS_JS, timeout=5) or {}
|
||||
if client.is_deleted:
|
||||
return
|
||||
try:
|
||||
prefs = await ui.run_javascript(PREFS_JS, timeout=5) or {}
|
||||
except TimeoutError:
|
||||
prefs = {"lang": fallback.lang}
|
||||
if client.is_deleted:
|
||||
return
|
||||
connecting.delete()
|
||||
AdminPage(service, identity, prefs, tab_from_request(request)).build()
|
||||
|
||||
|
||||
@@ -64,6 +75,14 @@ def tab_from_request(request: Request) -> str:
|
||||
return tab if tab in TABS else "overview"
|
||||
|
||||
|
||||
def render_connecting(t: Translator) -> Element:
|
||||
with ui.element("div").classes("etl-connecting") as box:
|
||||
ui.spinner(size="28px").classes("etl-connecting-spinner")
|
||||
ui.label(t("connect.title")).classes("etl-connecting-title")
|
||||
ui.label(t("connect.slow")).classes("etl-connecting-hint")
|
||||
return box
|
||||
|
||||
|
||||
def render_forbidden(t: Translator) -> None:
|
||||
with ui.element("div").classes("etl-forbidden"):
|
||||
with ui.element("div").classes("etl-card etl-forbidden-card"):
|
||||
|
||||
+23
-12
@@ -7,11 +7,11 @@ from pathlib import Path
|
||||
|
||||
import main
|
||||
|
||||
from .config import SettingsStore
|
||||
from .config import Settings, SettingsStore
|
||||
from .connectors import build_client, build_storage, build_store, close_quietly
|
||||
|
||||
|
||||
def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int:
|
||||
def run(settings_path: Path, output_dir: Path, dry_run: bool, cache_dir: Path | None = None) -> int:
|
||||
settings = SettingsStore(settings_path).get()
|
||||
print(f"storage_mode={settings.storage_mode}")
|
||||
print(f"database_mode={'none' if dry_run else settings.database_mode}")
|
||||
@@ -23,28 +23,39 @@ def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int:
|
||||
history = None
|
||||
if store is not None and settings.history_enabled:
|
||||
history = main.StorageHistoryStore(storage, settings.history_root)
|
||||
if not dry_run and settings.history_keep_days > 0:
|
||||
try:
|
||||
removed = main.StorageHistoryStore(storage, settings.history_root).prune(settings.history_keep_days)
|
||||
except main.ProcessingError as exc:
|
||||
print(f"history_prune_error={exc}")
|
||||
else:
|
||||
for path in removed:
|
||||
print(f"history_removed={path}")
|
||||
main.process(source, output_dir, settings.lookback_days, store=store, history=history)
|
||||
cell_cache = main.CellDataCache(cache_dir) if cache_dir is not None else None
|
||||
output = main.process(
|
||||
source, output_dir, settings.lookback_days, store=store, history=history, cell_cache=cell_cache
|
||||
)
|
||||
if output is not None and not dry_run:
|
||||
prune_history(storage, settings)
|
||||
finally:
|
||||
close_quietly(storage)
|
||||
return 0
|
||||
|
||||
|
||||
def prune_history(storage: main.FileStorage, settings: Settings) -> None:
|
||||
"""Apply history retention after a new group was stored. The data is already saved, so a failure is only reported."""
|
||||
if settings.history_keep_days <= 0:
|
||||
return
|
||||
try:
|
||||
removed = main.StorageHistoryStore(storage, settings.history_root).prune(settings.history_keep_days)
|
||||
except Exception as exc:
|
||||
print(f"history_prune_error={type(exc).__name__}: {exc}")
|
||||
return
|
||||
for path in removed:
|
||||
print(f"history_removed={path}")
|
||||
|
||||
|
||||
def entry(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Run one InterferenceETL pass with the saved app settings")
|
||||
parser.add_argument("--settings", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--cache", type=Path, help="directory for parsed CellData workbooks")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
return run(args.settings, args.output, args.dry_run)
|
||||
return run(args.settings, args.output, args.dry_run, args.cache)
|
||||
except main.ProcessingError as exc:
|
||||
print(f"error={exc}", file=sys.stderr, flush=True)
|
||||
return 1
|
||||
|
||||
Reference in New Issue
Block a user