"""公开远程配置 — 供抖音/微信真机拉配置(合法域名 + 有效证书)。 门户 nomadro.cn 证书与主机名不匹配,真机会 TLS 失败; 开发者工具不校验证书所以看起来正常。 走 dyapi.nomadro.cn / api.nomadro.cn(已在 request 合法域名且证书 OK)。 实时通道: - GET /api/config/stream → SSE(H5 / 门户 EventSource) - WS /api/config/ws → WebSocket(微信小程序 Taro.connectSocket) - GET /api/config/meta → 轮询兜底 """ from __future__ import annotations import asyncio import json from typing import Any from fastapi import APIRouter, WebSocket, WebSocketDisconnect from fastapi.responses import JSONResponse, StreamingResponse from ebook_svc.services.config_live import fanout, notify_config_changed, read_config_meta from ebook_svc.services.public_config_snapshot import PublicConfigSnapshot from ebook_svc.services.tt_platform_config import resolve_config_file router = APIRouter(tags=["public-config"]) _snapshot = PublicConfigSnapshot() _NO_STORE = { "Cache-Control": "no-store, no-cache, must-revalidate", "Access-Control-Allow-Origin": "*", } def _read_full_config() -> dict[str, Any]: return _snapshot.read(resolve_config_file()) def _config_response() -> JSONResponse: config = _read_full_config() return JSONResponse( content={"ok": True, "source": "file", "config": config}, headers=_NO_STORE, ) @router.get("/api/config") @router.get("/api/ebook/config") async def public_remote_config() -> JSONResponse: """对齐门户 GET /api/config:{ ok, source, config }。""" return _config_response() @router.post("/api/config") @router.post("/api/ebook/config") @router.post("/api/config/pull") @router.post("/api/ebook/config/pull") async def public_remote_config_pull() -> JSONResponse: """POST 拉全量:微信小程序会强缓存 GET,开关热更新必须走 POST。""" return _config_response() @router.get("/api/config/meta") @router.get("/api/ebook/config/meta") async def public_remote_config_meta() -> JSONResponse: meta = read_config_meta() return JSONResponse(content=meta, headers=_NO_STORE) @router.get("/api/config/stream") @router.get("/api/ebook/config/stream") async def public_remote_config_stream() -> StreamingResponse: """SSE:后台改 remote-config → 立刻推 version/updatedAt。""" queue = fanout.register() async def event_gen(): try: meta = notify_config_changed(read_config_meta(), source="sse-hello") yield f"event: config\ndata: {json.dumps(meta, ensure_ascii=False)}\n\n" while True: try: payload = await asyncio.wait_for(queue.get(), timeout=15.0) yield f"event: config\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n" except asyncio.TimeoutError: yield ": ping\n\n" finally: fanout.unregister(queue) return StreamingResponse( event_gen(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache, no-transform", "Connection": "keep-alive", "X-Accel-Buffering": "no", "Access-Control-Allow-Origin": "*", }, ) @router.websocket("/api/config/ws") @router.websocket("/api/ebook/config/ws") async def public_remote_config_ws(ws: WebSocket) -> None: """WebSocket:微信小程序实时配置(无 EventSource)。""" await ws.accept() queue = fanout.register() try: meta = notify_config_changed(read_config_meta(), source="ws-hello") await ws.send_text(json.dumps({"type": "config", **meta}, ensure_ascii=False)) async def pump_out() -> None: while True: try: payload = await asyncio.wait_for(queue.get(), timeout=20.0) await ws.send_text( json.dumps({"type": "config", **payload}, ensure_ascii=False) ) except asyncio.TimeoutError: await ws.send_text(json.dumps({"type": "ping"})) async def pump_in() -> None: while True: raw = await ws.receive_text() # 客户端可发 {"type":"pull"} 强制再推当前 meta try: msg = json.loads(raw) if raw else {} except Exception: msg = {} if isinstance(msg, dict) and msg.get("type") in ("pull", "hello", "ping"): cur = read_config_meta() await ws.send_text( json.dumps({"type": "config", **cur, "source": "pull"}, ensure_ascii=False) ) tasks = [asyncio.create_task(pump_out()), asyncio.create_task(pump_in())] try: done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) for task in done: task.result() finally: for task in tasks: task.cancel() await asyncio.gather(*tasks, return_exceptions=True) except WebSocketDisconnect: pass except Exception: try: await ws.close() except Exception: pass finally: fanout.unregister(queue)