自动登录接口 + 有状态端容器化部署 + 三服务合并 openapi 导出
自动登录(此前只能人工跑 scripts/login.py 再 /api/auth/reload):
- 新增 POST /api/auth/login:动作顺序与下单前的 require_logged_in 一致(探测 →
未登录则按 account.yaml 登一次 → 再探测),已登录直接跳过不白起浏览器。
刻意**不抛 5001**:失败以 logged_in=false + 各站 detail 正常返回,调用方自己
决定是人工接管还是换账号。
- 新增 RAKUTEN_AUTO_LOGIN_ON_START(默认 false):启动即准备登录态,为容器部署
而存在(镜像里没有落盘的 storage_state)。做成后台任务而非启动阻塞——登录最长
等 relogin_timeout_seconds(默认 300s,撞验证码时在等人工),阻塞会让 /health
在这段时间里连端口都不通;关服务时 cancel 掉在途的那次。
- 自动登录不绕过站点校验:凭据是用户自己配在 account.yaml 里的,代填进站点自己的
登录表单,撞 reCAPTCHA / 设备验证会停在有头浏览器等人工,等不到就超时失败。
容器化部署(新增 Dockerfile.trading + docker-compose.yml):
- 有状态端单独出镜像不是为了整洁:下单/结算必须用**有头** Chromium(headless 会让
结算 SPA 失灵),镜像要带 Xvfb + 日文字体 + 给人工接管用的可选 x11vnc,抓取镜像
没有这些。网关复用同一镜像只换 command。
- Jenkinsfile 一条流水线产出两个镜像,BUILD_SCRAPING / BUILD_TRADING 两个开关控制。
- .dockerignore 补上 account.yaml / .auth/ / .browser-data/ / data/:明文密码+卡号、
可直接冒充账号的 cookie、带登录态的浏览器 profile、含真实 PII 的证据快照,都不该
进镜像也不该进 build context,运行时一律走挂载。
- .env.example 里 RAKUTEN_AUTO_LOGIN_ON_START 刻意留成注释:compose 的变量插值与
env_file 读的是同一个 ./.env,这里写成显式值会让 compose 的 `${...:-true}` 失效,
按 compose 文件头「cp .env.example .env」走反而不会自动登录。
openapi 导出(scripts/export_openapi.py):三服务合并成一份可直接导入 Apifox /
Postman 的文档,每条接口带 operation 级 servers(不必手动切端口)。鉴权标注是遍历
FastAPI 依赖树认出真的挂了 require_bearer_token 的接口,不按路径猜。
openapi.json 本身仍是 gitignore 的本地生成物,因此 tests/test_openapi_export.py
只在内存里校验合并逻辑(三服务覆盖、operation 级 servers、除 /health 外全部标鉴权、
operationId 唯一、$ref 可解析),不断言「文件内容 == 当前导出结果」——CI 的全新
clone 里没有这个文件,那种断言必然失败。代价是「改了接口忘了重新导出」没有自动
兜底,得手动跑 --check,已在 README 里点明。
398 测试全绿;另单独验证过缺 openapi.json 时该文件 5 个用例仍通过(CI 场景)。
compose 的变量插值行为只按文档核对,本机没有 docker 未能实测。
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,17 +1,22 @@
|
||||
"""登录态路由:查询与重新加载账号登录态
|
||||
"""登录态路由:查询、自动登录与重新加载账号登录态
|
||||
|
||||
抓取接口全部匿名,只有加购与下单需要账号。登录本身不在这里做——乐天登录要过
|
||||
reCAPTCHA 与设备验证,由 `scripts/login.py` 起有头浏览器人工完成一次,
|
||||
本服务只读取落盘的 cookie。这里提供的是运维视角的两个动作:
|
||||
抓取接口全部匿名,只有加购与下单需要账号。这里是运维视角的三个动作:
|
||||
|
||||
- `/api/auth/status`:现在还登录着吗(默认真实打一次请求探测,不看缓存)
|
||||
- `/api/auth/login`:未登录时按 account.yaml 自动登录一次(撞验证码要人工接管)
|
||||
- `/api/auth/reload`:人工重新登录后,免重启服务重新读取登录态
|
||||
|
||||
自动登录不是「绕过校验」:账号密码是用户自己配在 account.yaml 里的,代填进站点
|
||||
自己的登录表单;撞 reCAPTCHA / 设备验证时流程会停在有头浏览器上等人工完成,
|
||||
等不到就超时失败(容器部署时用 VNC 接管,见 docker-compose.yml)。
|
||||
"""
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.shared.api import ApiResponse, get_container, require_bearer_token
|
||||
from app.trading.container import TradingContainer
|
||||
from app.trading.models import (
|
||||
AuthLoginData,
|
||||
AuthLoginRequest,
|
||||
AuthReloadData,
|
||||
AuthReloadRequest,
|
||||
AuthSiteStatus,
|
||||
@@ -43,8 +48,9 @@ async def auth_status(
|
||||
不需要这次网络往返时传 `refresh=false`,此时返回上一次探测的缓存结果
|
||||
(`logged_in` 为 null 表示从未探测过)。
|
||||
|
||||
`logged_in=false` 时,加购与下单接口会直接返回 5001,需要重新跑
|
||||
`scripts/login.py --site <site>` 后调用 `/api/auth/reload`。
|
||||
`logged_in=false` 时,加购与下单接口会直接返回 5001。恢复办法:调
|
||||
`/api/auth/login` 让服务自己登一次,或人工跑 `scripts/login.py --site <site>`
|
||||
后调 `/api/auth/reload`。
|
||||
"""
|
||||
sites = [payload.site.value] if payload.site else list(container.auth_session.sites)
|
||||
statuses = []
|
||||
@@ -64,6 +70,57 @@ async def auth_status(
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/login",
|
||||
response_model=ApiResponse[AuthLoginData],
|
||||
dependencies=[Depends(require_bearer_token)],
|
||||
)
|
||||
async def auth_login(
|
||||
payload: AuthLoginRequest,
|
||||
container: TradingContainer = Depends(get_container),
|
||||
) -> ApiResponse[AuthLoginData]:
|
||||
"""按 account.yaml 自动登录(已登录则跳过)
|
||||
|
||||
动作顺序与加购/下单前的 `require_logged_in` 完全一致,只是把它单独暴露出来,
|
||||
便于部署后主动把登录态准备好、以及登录态掉了之后手动救一次:
|
||||
|
||||
1. 真实探测一次登录态;已登录直接返回(不会白起一次浏览器)
|
||||
2. 未登录 → 读 account.yaml 默认账号跑登录流程(同站点串行)
|
||||
3. 再探测一次,返回最终结论
|
||||
|
||||
这里**不抛 5001**:登录失败会以 `logged_in=false` + 各站 detail 正常返回,
|
||||
调用方据此决定是人工接管还是换账号。`relogin_enabled=false` 或 account.yaml
|
||||
缺失时同样返回 false(服务端日志里有具体原因)。
|
||||
|
||||
单次调用最长耗时由 `RAKUTEN_RELOGIN_TIMEOUT_SECONDS`(默认 300s)决定——
|
||||
撞验证码时流程要在有头浏览器上等人工,别拿短超时的客户端调它。
|
||||
"""
|
||||
sites = [payload.site.value] if payload.site else list(container.auth_session.sites)
|
||||
|
||||
attempted: dict[str, bool] = {}
|
||||
statuses: list[AuthSiteStatus] = []
|
||||
for site in sites:
|
||||
status = await container.auth_session.check(site)
|
||||
if status.logged_in:
|
||||
attempted[site] = False
|
||||
else:
|
||||
attempted[site] = True
|
||||
if await container.auth_session.try_relogin(site):
|
||||
status = await container.auth_session.check(site)
|
||||
statuses.append(_to_model(status))
|
||||
|
||||
return ApiResponse[AuthLoginData](
|
||||
success=True,
|
||||
msg="success",
|
||||
data=AuthLoginData(
|
||||
logged_in=all(status.logged_in for status in statuses),
|
||||
relogin_attempted=attempted,
|
||||
sites=statuses,
|
||||
),
|
||||
code=0,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/reload",
|
||||
response_model=ApiResponse[AuthReloadData],
|
||||
|
||||
@@ -80,6 +80,34 @@ def build_container() -> TradingContainer:
|
||||
return container
|
||||
|
||||
|
||||
async def auto_login_on_start(container: TradingContainer) -> None:
|
||||
"""启动后自动把登录态准备好(RAKUTEN_AUTO_LOGIN_ON_START=true 时)
|
||||
|
||||
为容器部署而存在:镜像里没有落盘的 storage_state,不希望每次新起容器都得先
|
||||
在宿主机跑一遍 scripts/login.py。逐站点探测,未登录就按 account.yaml 登一次。
|
||||
|
||||
刻意做成后台任务而不是启动阻塞:登录最长要等 relogin_timeout_seconds(默认
|
||||
300s,撞验证码时在等人工),阻塞会让 /health 在这段时间里连端口都不通。
|
||||
任何失败都只记日志——服务照常提供 /health 与 /api/auth/*,人工接管后调
|
||||
/api/auth/login 重试即可。
|
||||
"""
|
||||
for site in container.auth_session.sites:
|
||||
try:
|
||||
status = await container.auth_session.check(site)
|
||||
if status.logged_in:
|
||||
logger.info("启动自动登录跳过:site=%s 已是登录态", site)
|
||||
continue
|
||||
logger.info("启动自动登录:site=%s 当前未登录(%s)", site, status.detail)
|
||||
if await container.auth_session.try_relogin(site):
|
||||
status = await container.auth_session.check(site)
|
||||
logger.info(
|
||||
"启动自动登录结束:site=%s logged_in=%s detail=%s",
|
||||
site, status.logged_in, status.detail,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("启动自动登录异常:site=%s(服务继续运行)", site)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""应用生命周期管理:登录态会话 + 站点交互器(必起)+ 可选 worker"""
|
||||
@@ -101,6 +129,14 @@ async def lifespan(app: FastAPI):
|
||||
assert container.site is not None
|
||||
await container.site.start() # type: ignore[union-attr]
|
||||
|
||||
login_task: asyncio.Task | None = None
|
||||
if container.settings.auto_login_on_start:
|
||||
login_task = asyncio.create_task(
|
||||
auto_login_on_start(container), name="trading-auto-login"
|
||||
)
|
||||
else:
|
||||
logger.info("未开启 RAKUTEN_AUTO_LOGIN_ON_START,启动时不自动登录")
|
||||
|
||||
worker_task: asyncio.Task | None = None
|
||||
if container.worker_runner is not None:
|
||||
# 顺序:本地 DB 在 worker 写证据前先就绪;SiteInteractor 已在外层启动
|
||||
@@ -123,6 +159,13 @@ async def lifespan(app: FastAPI):
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if login_task is not None and not login_task.done():
|
||||
# 关服务时正在登的那次不要了:浏览器由 login_one 自己的 async with 收尾
|
||||
login_task.cancel()
|
||||
try:
|
||||
await login_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
if worker_task is not None:
|
||||
container.worker_runner.stop() # type: ignore[union-attr]
|
||||
worker_task.cancel()
|
||||
|
||||
@@ -59,6 +59,25 @@ class AuthReloadData(BaseModel):
|
||||
sites: list[AuthSiteStatus] = Field(default_factory=list)
|
||||
|
||||
|
||||
class AuthLoginRequest(BaseModel):
|
||||
"""触发自动登录请求"""
|
||||
|
||||
site: AuthSite | None = None # 不传则对所有已配置站点各跑一次
|
||||
|
||||
|
||||
class AuthLoginData(BaseModel):
|
||||
"""触发自动登录响应
|
||||
|
||||
logged_in 是本次动作的最终结论(所有涉及站点都登录着才为 true);
|
||||
relogin_attempted 标出哪些站点真的跑了登录流程——已登录的站点直接跳过,
|
||||
不会白起一次浏览器。
|
||||
"""
|
||||
|
||||
logged_in: bool
|
||||
relogin_attempted: dict[str, bool] = Field(default_factory=dict)
|
||||
sites: list[AuthSiteStatus] = Field(default_factory=list)
|
||||
|
||||
|
||||
class TradingHealthData(BaseModel):
|
||||
"""交易服务健康检查响应数据
|
||||
|
||||
|
||||
Reference in New Issue
Block a user