nomadro/apps/api/services/ebook_svc/routers/ops_admin.py
Eric 308974bf5e Harden platform upgrade: ops admin, live config, shared service proxy, and smoke deploys.
Ship Operations console polish, PocketBase social fixtures, and portal join-leads without local DBs or probe scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 01:20:55 +08:00

113 lines
4.0 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.

"""运营:ntfy 状态 / 试推 — admin.nomadro.com 与 .cn 共用。"""
from __future__ import annotations
import asyncio
import os
import shutil
import time
from datetime import datetime, timezone
from pathlib import Path
import httpx
from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from ebook_svc.config import settings
from ebook_svc.core.security import require_admin
from ebook_svc.services import ntfy as ntfy_svc
router = APIRouter(prefix="/api/admin/ops", tags=["ops-admin"])
async def _probe(client: httpx.AsyncClient, name: str, url: str) -> dict:
started = time.monotonic()
try:
response = await client.get(url)
ok = 200 <= response.status_code < 300
if ok:
try:
payload = response.json()
ok = isinstance(payload, dict) and payload.get('ok') is True
except ValueError:
ok = False
status = response.status_code
except httpx.HTTPError:
ok, status = False, None
return {"name": name, "ok": ok, "status": status,
"latencyMs": round((time.monotonic() - started) * 1000)}
def _resources() -> dict:
disk = shutil.disk_usage(Path.cwd())
memory = None
try:
values = {}
for line in Path('/proc/meminfo').read_text().splitlines():
key, value = line.split(':', 1)
values[key] = int(value.split()[0]) * 1024
total = values['MemTotal']
available = values['MemAvailable']
memory = {"totalBytes": total, "usedBytes": total - available,
"usedPercent": round((total - available) * 100 / total, 1)}
except (OSError, ValueError, KeyError):
pass
try:
load = list(os.getloadavg())
except (AttributeError, OSError):
load = None
return {"disk": {"totalBytes": disk.total, "usedBytes": disk.used,
"usedPercent": round(disk.used * 100 / disk.total, 1)},
"memory": memory, "loadAverage": load, "cpuCount": os.cpu_count()}
@router.get('/health')
async def ops_health(_: str = Depends(require_admin)):
# Fixed loopback targets; callers cannot probe arbitrary hosts or paths.
async with httpx.AsyncClient(timeout=3.0, trust_env=False) as client:
checks = await asyncio.gather(
_probe(client, 'Next.js 门户', 'http://127.0.0.1:4003/api/health'),
_probe(client, '业务 API', 'http://127.0.0.1:8010/health'),
_probe(client, '社区服务', 'http://127.0.0.1:8020/health'),
)
resources = await asyncio.to_thread(_resources)
return JSONResponse({"ok": all(c['ok'] for c in checks), "checks": checks,
"resources": resources,
"checkedAt": datetime.now(timezone.utc).isoformat()},
headers={"Cache-Control": "no-store"})
class NtfyTestBody(BaseModel):
title: str = Field(default="[WebAdmin] 试推", max_length=80)
message: str = Field(default="admin.nomadro.com 通知通路正常", max_length=500)
priority: int = Field(default=3, ge=1, le=5)
tags: str | None = Field(default="white_check_mark,globe_with_meridians")
@router.get("/ntfy")
async def ntfy_status(_: str = Depends(require_admin)) -> dict:
base = (settings.ntfy_base_url or "").rstrip("/")
topic = (settings.ntfy_topic or "").strip().strip("/")
return {
"enabled": bool(settings.ntfy_enabled),
"baseUrl": base,
"topic": topic,
"hasToken": bool((settings.ntfy_token or "").strip()),
"publicHint": base + "/" + topic if base.startswith("https://") and topic else "",
}
@router.post("/ntfy/test")
async def ntfy_test(body: NtfyTestBody, _: str = Depends(require_admin)) -> dict:
ok = await ntfy_svc.notify(
body.message,
title=body.title[:80],
tags=body.tags,
priority=body.priority,
)
return {
"ok": ok,
"enabled": bool(settings.ntfy_enabled),
"topic": (settings.ntfy_topic or "").strip(),
}