diff --git a/.dockerignore b/.dockerignore index b82542c..dff0aa8 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,10 +14,18 @@ __pycache__/ .env .env.* !.env.example +# 这三样都不进镜像(运行时用挂载提供),也不该被送进 build context: +# account.yaml 是明文密码+卡号,.auth 是可直接冒充账号的 cookie, +# .browser-data 是带登录态的浏览器 profile。 +account.yaml +.auth/ +.browser-data/ # 运行时产物 logs/ .probe/ +# 订单库、证据快照(含真实姓名地址等 PII),只走挂载 +data/ # 测试不进镜像(Jenkinsfile 里单独跑) tests/ @@ -32,6 +40,7 @@ README.md # CI / 部署文件本身 Dockerfile +Dockerfile.* .dockerignore Jenkinsfile docker-compose*.yml diff --git a/.env.example b/.env.example index eef3bcc..b08cd14 100644 --- a/.env.example +++ b/.env.example @@ -86,6 +86,20 @@ RAKUTEN_ORDER_MAX_TOTAL_YEN=30000 RAKUTEN_ORDER_MONITOR_POLL_INTERVAL_SECONDS=10800 RAKUTEN_ORDER_MONITOR_MAX_CHECKS=80 +# 登录态失效时是否自动重登(需要项目根有 account.yaml,含明文密码)。 +# 关闭时登录态一掉就抛 5001 / 转 needs_human,需要人工跑 scripts/login.py。 +RAKUTEN_RELOGIN_ENABLED=true +# 自动登录(含撞验证码时等人工接管)的最长总耗时(秒)。无人值守的机器可以调小 +# (如 60)以尽快失败转 needs_human。 +RAKUTEN_RELOGIN_TIMEOUT_SECONDS=300 +# 启动时是否自动登录一次:起服务即按 account.yaml 把登录态准备好,不必先在宿主机跑 +# scripts/login.py。后台执行不阻塞端口,失败只记日志。 +# **刻意留成注释**:裸机跑不开(代码默认 false,别在开发机上一启动就弹浏览器), +# 容器部署由 docker-compose.yml 给 true。这里一旦写成显式值,compose 里的 +# `${RAKUTEN_AUTO_LOGIN_ON_START:-true}` 就会读到 .env 的值而失效——compose 的变量 +# 插值和 env_file 读的是同一个 ./.env。要手动覆盖时才取消注释。 +# RAKUTEN_AUTO_LOGIN_ON_START=false + # ---- 以下仅下单任务网关使用 ---- # 任务队列 SQLite 文件路径(相对项目根目录)。务必放在持久化卷上,丢了等于 # 丢了一批下单任务。详见 docs/order-gateway.md。 diff --git a/Dockerfile.trading b/Dockerfile.trading new file mode 100644 index 0000000..97c0890 --- /dev/null +++ b/Dockerfile.trading @@ -0,0 +1,176 @@ +# syntax=docker/dockerfile:1.7 +# +# 有状态端镜像:交易服务(下单购买 + 订单查询/监控),默认 python -m app.trading.main,:31108。 +# +# 为什么不复用根目录 Dockerfile(抓取服务镜像): +# 1. 下单/结算/加购必须用**有头** Chromium——site_interact.py 里 headless 是硬编码 +# False(2026-08-14 实测:无头会让购物车/结算 SPA 失灵)。抓取镜像里没有任何 X +# 显示,交易进程一 launch 就崩。这里内置 Xvfb 虚拟显示解决。 +# 2. 这条链路上有设计好的人工接管点(登录验证码、3DS/OTP、needs_human),远程主机上 +# 必须能真的看见那个浏览器窗口 → 内置可选 x11vnc(默认关闭)。 +# 3. 页面是日文,证据截图要有日文字形 → fonts-ipafont(抓取侧只取 HTML,不需要)。 +# +# 同一镜像也能跑下单任务网关(python -m app.gateway.main,:31109):网关不碰浏览器, +# 用 RAKUTEN_XVFB_ENABLED=false 关掉虚拟显示即可。 +# +# 交易服务与网关都**只能单实例**:登录态 cookie 全局唯一、订单监控是常驻轮询、 +# SQLite 单连接。不要 --scale,也不要在前面挂多副本负载均衡。 + +# ----------------------------- builder ----------------------------- +FROM registry.jerryyan.top/library/python:3.13-slim AS builder + +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + UV_LINK_MODE=copy \ + UV_COMPILE_BYTECODE=1 \ + # 国内 PyPI 镜像:避免从官方 PyPI 拉包缓慢 + UV_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ + +# 与根 Dockerfile 相同来源:python3.13-* 标签的 uv 在 /usr/local/bin/ +COPY --from=registry-ghcr.jerryyan.top/astral-sh/uv:python3.13-bookworm-slim /usr/local/bin/uv /usr/local/bin/uvx /usr/local/bin/ + +WORKDIR /app + +# 只装运行期依赖:playwright / aiosqlite 都在 [project].dependencies 主表里, +# 交易服务不需要 --extra browser(那是抓取侧的可选兜底)。 +COPY uv.lock pyproject.toml ./ +RUN --mount=type=cache,target=/root/.cache/uv \ + uv sync --frozen --no-dev + +COPY app ./app +RUN --mount=type=cache,target=/root/.cache/uv \ + uv sync --frozen --no-dev + +# ----------------------------- runtime ----------------------------- +FROM registry.jerryyan.top/library/python:3.13-slim AS runtime + +ENV PYTHONUNBUFFERED=1 \ + PYTHONDONTWRITEBYTECODE=1 \ + VIRTUAL_ENV=/app/.venv \ + PATH="/app/.venv/bin:${PATH}" \ + PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \ + PLAYWRIGHT_DOWNLOAD_HOST=https://cdn.npmmirror.com/binaries/playwright \ + # 落库时间戳全是 UTC aware(local_db/task_queue 用 datetime.now(timezone.utc)), + # 这里设日本时区只影响日志与调试快照文件名的可读性,不改变任何持久化语义。 + TZ=Asia/Tokyo \ + # 虚拟显示:Chromium 有头模式必须有 DISPLAY。跑网关时置 false 可完全跳过 Xvfb。 + DISPLAY=:99 \ + RAKUTEN_XVFB_ENABLED=true \ + RAKUTEN_XVFB_SCREEN=1280x1024x24 \ + # 远程接管(验证码 / 3DS / needs_human 时肉眼看浏览器):默认关闭。 + # 开启前务必设 RAKUTEN_VNC_PASSWORD,且端口只对内网/SSH 隧道开放—— + # 这个屏幕上是已登录的真实账号与结算页。 + RAKUTEN_VNC_ENABLED=false \ + RAKUTEN_VNC_PORT=5900 \ + RAKUTEN_TRADING_HOST=0.0.0.0 \ + RAKUTEN_TRADING_PORT=31108 \ + # 与根镜像保持一致:默认导出 traces 到自建 OTLP(裸跑无鉴权), + # 服务名由 app/trading/main.py 显式设为 rakuten-trading。 + RAKUTEN_OTEL_ENABLED=true \ + RAKUTEN_OTEL_ENDPOINT=https://oltp.jerryyan.top/v1/traces + +# 有头 Chromium 运行依赖 + Xvfb + 日文字体。 +# 显式列包而不用 `playwright install-deps`(后者装的是一整套 apt 源里的当前版本, +# 构建结果随源漂移)。Debian t64 过渡把一批库改名(libasound2 → libasound2t64 等), +# 所以先整表装一次,失败再逐包回退试 ${pkg}t64,让镜像在 bookworm/trixie 基础镜像上都能建起来。 +RUN set -eu; \ + { \ + if [ -f /etc/apt/sources.list ]; then \ + sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list; \ + fi; \ + if [ -f /etc/apt/sources.list.d/debian.sources ]; then \ + sed -i 's|deb.debian.org|mirrors.aliyun.com|g; s|security.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources; \ + fi; \ + }; \ + PKGS="ca-certificates curl tzdata \ + xvfb x11vnc \ + fonts-liberation fonts-ipafont-gothic fonts-ipafont-mincho \ + libasound2 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 \ + libcairo2 libcairo-gobject2 libcups2 libdbus-1-3 libdrm2 libgbm1 \ + libgdk-pixbuf-2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 \ + libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 \ + libxkbcommon0 libxrandr2 libxshmfence1 xdg-utils"; \ + apt-get update; \ + if ! apt-get install -y --no-install-recommends $PKGS; then \ + for pkg in $PKGS; do \ + apt-get install -y --no-install-recommends "$pkg" \ + || apt-get install -y --no-install-recommends "${pkg}t64"; \ + done; \ + fi; \ + rm -rf /var/lib/apt/lists/* + +# 非 root 账号(uid/gid 与根镜像一致,方便共用宿主机上的 .auth / data 目录属主) +RUN groupadd --system --gid 10001 rakuten \ + && useradd --system --uid 10001 --gid rakuten --no-create-home --shell /usr/sbin/nologin rakuten + +WORKDIR /app + +COPY --from=builder /app/.venv /app/.venv +COPY --from=builder /app/app /app/app +# 只带 login.py:容器里首次产出登录态要用它(配合 VNC 人工过验证码), +# scripts/ 下其余都是探针脚本,属开发工具,不进镜像。 +COPY scripts/login.py /app/scripts/login.py + +# 入口:拉起 Xvfb(可选 x11vnc)后 exec 真正的进程,保证信号直达 PID 1。 +COPY --chmod=0755 <<'ENTRYPOINT_SH' /usr/local/bin/rakuten-entrypoint.sh +#!/bin/sh +set -e + +if [ "${RAKUTEN_XVFB_ENABLED:-true}" = "true" ]; then + screen_num="${DISPLAY#:}" + socket="/tmp/.X11-unix/X${screen_num%%.*}" + Xvfb "$DISPLAY" -screen 0 "${RAKUTEN_XVFB_SCREEN:-1280x1024x24}" -nolisten tcp & + + # 等 X socket 就绪再放行;否则 Chromium 会以 "Missing X server" 直接失败 + waited=0 + while [ ! -e "$socket" ]; do + waited=$((waited + 1)) + if [ "$waited" -ge 100 ]; then + echo "Xvfb 10 秒内未就绪($socket 不存在),放弃启动" >&2 + exit 1 + fi + sleep 0.1 + done + echo "Xvfb 已就绪:DISPLAY=$DISPLAY screen=${RAKUTEN_XVFB_SCREEN:-1280x1024x24}" + + if [ "${RAKUTEN_VNC_ENABLED:-false}" = "true" ]; then + # 有密码就用密码,没有则明文无鉴权——后者只允许在 SSH 隧道/内网里用 + if [ -n "${RAKUTEN_VNC_PASSWORD:-}" ]; then + mkdir -p /tmp/.vnc + x11vnc -storepasswd "$RAKUTEN_VNC_PASSWORD" /tmp/.vnc/passwd >/dev/null 2>&1 + auth_args="-rfbauth /tmp/.vnc/passwd" + else + echo "警告:RAKUTEN_VNC_ENABLED=true 但未设 RAKUTEN_VNC_PASSWORD,VNC 无鉴权" >&2 + auth_args="-nopw" + fi + # shellcheck disable=SC2086 + x11vnc -display "$DISPLAY" -forever -shared -bg -quiet \ + -rfbport "${RAKUTEN_VNC_PORT:-5900}" $auth_args + echo "x11vnc 已启动:端口 ${RAKUTEN_VNC_PORT:-5900}(屏幕上是真实已登录账号,勿暴露公网)" + fi +fi + +exec "$@" +ENTRYPOINT_SH + +# 可写目录:logs(Loguru)、data(订单 SQLite + 证据)、.auth(登录态 cookie)、 +# .browser-data(login.py 的持久化浏览器目录)、/ms-playwright(Chromium 二进制)、 +# /tmp/.X11-unix(Xvfb socket,非 root 也要能建) +RUN mkdir -p /app/logs /app/data /app/.auth /app/.browser-data /ms-playwright /tmp/.X11-unix \ + && chmod 1777 /tmp/.X11-unix \ + && chown -R rakuten:rakuten /app /ms-playwright + +USER rakuten + +RUN /app/.venv/bin/playwright install chromium + +# /health 只读缓存登录态,不触发站点请求,适合高频探活。 +# 端口取 RAKUTEN_HEALTH_PORT,未设时用交易端口;跑网关的容器把它设成 31109。 +HEALTHCHECK --interval=30s --timeout=5s --start-period=45s --retries=3 \ + CMD curl -fsS http://127.0.0.1:${RAKUTEN_HEALTH_PORT:-${RAKUTEN_TRADING_PORT}}/health || exit 1 + +# 31108 交易服务,31109 下单任务网关(同镜像换 command),5900 可选 VNC +EXPOSE 31108 31109 5900 + +ENTRYPOINT ["/usr/local/bin/rakuten-entrypoint.sh"] +CMD ["python", "-m", "app.trading.main"] diff --git a/Jenkinsfile b/Jenkinsfile index e434745..03741c6 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,6 +1,12 @@ -// Jenkinsfile —— jp-rakuten(乐天 / ラクマ 抓取服务) +// Jenkinsfile —— jp-rakuten(抓取服务 + 有状态端) +// +// 一次构建出两个镜像,两者用途不同、不能互相替代: +// git.jerryyan.net/jp/rakuten-api ← Dockerfile 抓取服务(无状态可多开) +// git.jerryyan.net/jp/rakuten-trading ← Dockerfile.trading 有状态端(下单购买+订单查询) +// 有状态端单独出镜像是因为下单/结算必须用**有头** Chromium(headless 会让结算 SPA +// 失灵),镜像里要带 Xvfb + 日文字体 + 可选 x11vnc,抓取镜像没有这些。 +// 网关(app.gateway.main)复用 rakuten-trading 镜像,只是换 command。 // -// 默认 registry: git.jerryyan.net/jp/rakuten-api // 构建参数说明见各 stage 顶部;首次使用前请在 Jenkins 里配置凭据: // - git-credentials : 拉代码的 SSH / HTTPS 凭据 // - gitea-registry : docker login git.jerryyan.net 的凭据(username/password) @@ -18,10 +24,19 @@ pipeline { parameters { string(name: 'IMAGE_NAME', defaultValue: 'git.jerryyan.net/jp/rakuten-api', - description: '镜像完整名(含 registry host)') + description: '抓取服务镜像完整名(含 registry host)') + string(name: 'TRADING_IMAGE_NAME', + defaultValue: 'git.jerryyan.net/jp/rakuten-trading', + description: '有状态端(下单+订单查询,含网关)镜像完整名') string(name: 'IMAGE_TAG', defaultValue: '', - description: '自定义 tag;留空则用 -') + description: '自定义 tag;留空则用 -。两个镜像共用同一 tag') + booleanParam(name: 'BUILD_SCRAPING', + defaultValue: true, + description: '构建并推送抓取服务镜像') + booleanParam(name: 'BUILD_TRADING', + defaultValue: true, + description: '构建并推送有状态端镜像(体积大:含 Chromium + Xvfb,约 +700MB)') booleanParam(name: 'SKIP_TEST', defaultValue: false, description: '跳过单测(紧急发版用,正常构建不要勾)') @@ -82,7 +97,10 @@ pipeline { } } - stage('Build image') { + stage('Build image: scraping') { + when { + expression { return params.BUILD_SCRAPING } + } steps { sh """ docker build \ @@ -95,18 +113,49 @@ pipeline { } } - stage('Push image') { + stage('Build image: trading') { + when { + expression { return params.BUILD_TRADING } + } + // 有状态端镜像:Chromium + Xvfb + 日文字体,比抓取镜像明显大也明显慢, + // 首次构建(无缓存)拉 Chromium 二进制约 300MB + steps { + sh """ + docker build \ + -t ${params.TRADING_IMAGE_NAME}:${env.IMAGE_TAG} \ + -t ${params.TRADING_IMAGE_NAME}:latest \ + --label org.opencontainers.image.revision=${env.GIT_SHA} \ + --label org.opencontainers.image.version=${env.IMAGE_TAG} \ + -f Dockerfile.trading . + """ + } + } + + stage('Push images') { + when { + expression { return params.BUILD_SCRAPING || params.BUILD_TRADING } + } steps { withCredentials([usernamePassword( credentialsId: 'gitea-registry', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASS', )]) { - sh """ - echo "\$REGISTRY_PASS" | docker login git.jerryyan.net -u "\$REGISTRY_USER" --password-stdin - docker push ${env.IMAGE_NAME}:${env.IMAGE_TAG} - docker push ${env.IMAGE_NAME}:latest - """ + sh 'echo "$REGISTRY_PASS" | docker login git.jerryyan.net -u "$REGISTRY_USER" --password-stdin' + script { + if (params.BUILD_SCRAPING) { + sh """ + docker push ${env.IMAGE_NAME}:${env.IMAGE_TAG} + docker push ${env.IMAGE_NAME}:latest + """ + } + if (params.BUILD_TRADING) { + sh """ + docker push ${params.TRADING_IMAGE_NAME}:${env.IMAGE_TAG} + docker push ${params.TRADING_IMAGE_NAME}:latest + """ + } + } } } } @@ -118,10 +167,14 @@ pipeline { sh """ docker rmi -f ${env.IMAGE_NAME}:${env.IMAGE_TAG} 2>/dev/null || true docker rmi -f ${env.IMAGE_NAME}:latest 2>/dev/null || true + docker rmi -f ${params.TRADING_IMAGE_NAME}:${env.IMAGE_TAG} 2>/dev/null || true + docker rmi -f ${params.TRADING_IMAGE_NAME}:latest 2>/dev/null || true """ } success { - echo "构建成功:${env.IMAGE_NAME}:${env.IMAGE_TAG}" + echo "构建成功:tag=${env.IMAGE_TAG}" + + (params.BUILD_SCRAPING ? " ${env.IMAGE_NAME}" : "") + + (params.BUILD_TRADING ? " ${params.TRADING_IMAGE_NAME}" : "") } failure { echo "构建失败,请查看上方日志" diff --git a/README.md b/README.md index d023233..57c4ec2 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,12 @@ PC UA 在搜索页、详情页、店铺页上都能拿到完整模板。因此 | --- | --- | | `GET /health` | 健康检查,含乐天账号登录态(只读缓存,不打站点) | | `POST /api/auth/status` | 查询登录态,默认真实探测一次 | +| `POST /api/auth/login` | 按 `account.yaml` 自动登录(已登录则跳过;撞验证码要人工接管) | | `POST /api/auth/reload` | 人工重新登录后免重启换上新 cookie | +| `POST /api/cart/add` | 加购(`item_url` + 数量/规格/选项) | +| `POST /api/cart/status` | 购物车件数与登录态(轻量,不渲染整页) | +| `POST /api/cart/clear` | 清空购物车 | +| `POST /api/cart/remove` | 删除指定 `item_id` | 下单任务网关(:31109): @@ -147,6 +152,18 @@ PC UA 在搜索页、详情页、店铺页上都能拿到完整模板。因此 三个服务共用同一个 Bearer Token,错误码表也是同一份。 启动后分别在 `http://127.0.0.1:31107/docs`、`:31108/docs`、`:31109/docs` 查看 OpenAPI 文档。 +要一份能直接导入 Apifox / Postman 的合并文档,用仓库根的 `openapi.json`:三个服务的接口都在里面, +每条接口带 operation 级 `servers`(导入后不必手动切端口)与 Bearer 鉴权声明。它是 gitignore 的本地 +生成物(不进版本库),由脚本产出,别手改: + +```bash +.venv/Scripts/python.exe scripts/export_openapi.py # 重新导出 +.venv/Scripts/python.exe scripts/export_openapi.py --check # 校验是否已最新 +``` + +**改了接口记得手动重新导出**:因为文件不在版本库里,单测无法校验它是否过期(`tests/test_openapi_export.py` +只在内存里检查合并逻辑本身:三服务覆盖、operation 级 servers、鉴权标注、operationId 唯一、`$ref` 可解析)。 + ## 安装 ```bash @@ -182,6 +199,32 @@ uv sync --extra dev --extra browser cookie 落在 `.auth/`(已 gitignore,内含可直接冒充账号的凭据,不要提交或外传)。 后续重新登录后调 `POST /api/auth/reload` 换上新 cookie,不必重启服务。 +配了 `account.yaml` 的话不用每次手动登:`RAKUTEN_RELOGIN_ENABLED=true`(默认)时登录态失效会自动重登, +`RAKUTEN_AUTO_LOGIN_ON_START=true` 时服务启动就自己登一次,也可以随时调 `POST /api/auth/login` 触发。 +撞 reCAPTCHA / 设备验证时流程会停在有头浏览器上等人工完成,等不到就超时失败——自动登录只是代填 +`account.yaml` 里的凭据,不绕过站点校验。 + +## 容器部署 + +两个镜像,用途不能互换: + +| 镜像 | Dockerfile | 跑什么 | +| --- | --- | --- | +| `rakuten-api` | `Dockerfile` | 抓取服务(无状态,可多开) | +| `rakuten-trading` | `Dockerfile.trading` | 有状态端:交易服务(默认)与下单网关(换 `command`) | + +有状态端单独出镜像不是为了整洁:下单/结算必须用**有头** Chromium(`headless=True` 会让结算 SPA 失灵), +镜像里要带 Xvfb 虚拟显示、日文字体,以及给人工接管用的可选 x11vnc,抓取镜像没有这些。 + +```bash +docker compose up -d # 起交易服务(本地机侧) +docker compose --profile gateway up -d # 额外起下单网关(正式拓扑里它在服务器侧) +``` + +部署前置与挂载说明写在 `docker-compose.yml` 文件头:至少要有 `.env` 与 `account.yaml`, +`.auth/`、`data/`、`logs/` 走挂载持久化。Jenkins 上两个镜像由同一条流水线产出 +(`BUILD_SCRAPING` / `BUILD_TRADING` 两个开关控制)。 + ## 测试 ```bash diff --git a/app/shared/config.py b/app/shared/config.py index d17adaf..8b7e015 100644 --- a/app/shared/config.py +++ b/app/shared/config.py @@ -128,6 +128,11 @@ class Settings(BaseSettings): # worker 内触发时整个任务会被卡住这段时间,所以不宜过长;本地机无人值守时 # 可以设小(如 60)尽快失败转 needs_human。 relogin_timeout_seconds: int = 300 + # 启动时是否自动登录一次。容器部署用:镜像里没有落盘的 storage_state, + # 开启后启动即按 account.yaml 自己登一次,不必先在宿主机跑 scripts/login.py。 + # 后台执行(不阻塞 HTTP 端口),失败只记日志——服务照常提供 /health 与 + # /api/auth/*,撞验证码可人工接管后调 /api/auth/login 重试。 + auto_login_on_start: bool = False # ---- 下单任务网关(仅网关进程 app.gateway.main 使用)---- # 网关的 SQLite 文件路径(相对项目根目录)。任务队列与状态镜像都在这里, diff --git a/app/trading/api/routes/auth.py b/app/trading/api/routes/auth.py index 11c9f9b..739f5c1 100644 --- a/app/trading/api/routes/auth.py +++ b/app/trading/api/routes/auth.py @@ -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 ` 后调用 `/api/auth/reload`。 + `logged_in=false` 时,加购与下单接口会直接返回 5001。恢复办法:调 + `/api/auth/login` 让服务自己登一次,或人工跑 `scripts/login.py --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], diff --git a/app/trading/main.py b/app/trading/main.py index a9c28b4..481d38f 100644 --- a/app/trading/main.py +++ b/app/trading/main.py @@ -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() diff --git a/app/trading/models.py b/app/trading/models.py index 3ea6141..d3106b0 100644 --- a/app/trading/models.py +++ b/app/trading/models.py @@ -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): """交易服务健康检查响应数据 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e4fe835 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,128 @@ +# 有状态端部署(下单购买 + 订单查询/监控) +# +# 默认只起交易服务 trading(本地机侧:持登录态、执行下单、常驻订单监控): +# docker compose up -d +# 下单任务网关按设计部署在**服务器侧**(与抓取服务同机),是另一个部署单元, +# 所以放在 gateway profile 里,不会被默认启动。真要在这台机上一起跑(自包含 +# 联调 / 单机部署)时: +# docker compose --profile gateway up -d +# +# 两个服务都**只能单实例**:登录态 cookie 全局唯一、订单监控是常驻轮询、SQLite +# 单连接 + 全局并发度 1。不要 `--scale`,不要在前面挂多副本。 +# +# 部署前置(缺一样服务就跑不通,不是可选项): +# 1. cp .env.example .env,至少填 RAKUTEN_BEARER_TOKEN / RAKUTEN_ORDER_GATEWAY_URL / +# RAKUTEN_SCRAPER_BASE_URL(后两个留空则 worker 不启动,只剩购物车与登录态接口)。 +# 2. cp account.yaml.example account.yaml 并填真实凭据(session upgrade 复核密码、 +# 手机号补录、支付方式核对都要读它)。**必须先建文件再 up**,否则 Docker 会 +# 把这个挂载点当目录创建,容器里读到的是个空目录。 +# 3. 登录态 cookie(.auth/rakuten_state.json):**不必**先在宿主机准备—— +# RAKUTEN_AUTO_LOGIN_ON_START 默认开,容器起来就按 account.yaml 自己登一次。 +# 撞 reCAPTCHA / 设备验证会停在浏览器里等人工,这时把 RAKUTEN_VNC_ENABLED 设成 +# true(配 RAKUTEN_VNC_PASSWORD)连 127.0.0.1:5900 接管,完成后: +# curl -X POST -H "Authorization: Bearer $TOKEN" http://127.0.0.1:31108/api/auth/login +# 也可以照旧在宿主机跑 scripts/login.py 再挂载进来,两条路都行。 +# +# 敏感面:.auth/(可直接冒充账号的 cookie)、account.yaml(明文密码+卡号)、 +# data/(真实姓名地址等 PII 与证据快照)全在宿主机目录里,注意宿主机权限与备份加密。 + +services: + trading: + # 交易服务:加购 → 下单 → 付款 → 订单监控,以及 /api/auth/* /api/cart/* + image: ${RAKUTEN_TRADING_IMAGE:-git.jerryyan.net/jp/rakuten-trading}:${RAKUTEN_TRADING_TAG:-latest} + build: + context: . + dockerfile: Dockerfile.trading + container_name: rakuten-trading + restart: unless-stopped + # PID 1 用 docker-init:Chromium 会派生一堆子进程,崩溃时需要有人收尸 + init: true + # Chromium 默认 /dev/shm 只有 64MB,渲染稍重的结算页会直接 crash + shm_size: 1gb + # 停容器时给正在执行的下单任务留出收尾时间(uvicorn 关 lifespan → worker 停轮询 + # → 取消订单监控 → 关浏览器)。**停容器前最好先确认没有在途任务**:进程被硬杀 + # 时站点侧可能已经提交成功,本地没记录,恢复要走 verify_on_site 人工核对。 + stop_grace_period: 120s + env_file: + - .env + environment: + # 容器内必须监听 0.0.0.0,对外只从 127.0.0.1 映射(见 ports) + RAKUTEN_TRADING_HOST: 0.0.0.0 + RAKUTEN_TRADING_PORT: 31108 + RAKUTEN_HEALTH_PORT: 31108 + RAKUTEN_APP_ENV: prod + # worker 标识:默认取主机名,容器主机名是随机 ID,重建就变——显式固定, + # 便于在网关侧对上是哪台机在领任务 + RAKUTEN_WORKER_ID: ${RAKUTEN_WORKER_ID:-rakuten-trading-docker} + # 有头 Chromium 需要虚拟显示(镜像内 Xvfb),别关 + RAKUTEN_XVFB_ENABLED: "true" + # 启动即按 account.yaml 自动登录(后台跑,不阻塞端口)。撞 reCAPTCHA / 设备验证 + # 时会停在浏览器里等人工——那时开 VNC 接管,或事后调 POST /api/auth/login 重试。 + RAKUTEN_AUTO_LOGIN_ON_START: ${RAKUTEN_AUTO_LOGIN_ON_START:-true} + RAKUTEN_RELOGIN_ENABLED: ${RAKUTEN_RELOGIN_ENABLED:-true} + # 需要远程盯着浏览器(登录验证码、3DS、needs_human 人工接管)时改成 true, + # 并设 RAKUTEN_VNC_PASSWORD;端口只映射到 127.0.0.1,走 SSH 隧道访问 + RAKUTEN_VNC_ENABLED: ${RAKUTEN_VNC_ENABLED:-false} + RAKUTEN_VNC_PASSWORD: ${RAKUTEN_VNC_PASSWORD:-} + ports: + # 这些接口能操作真实账号,只对本机开放;要跨机访问请走内网地址或 SSH 隧道 + - "127.0.0.1:31108:31108" + - "127.0.0.1:5900:5900" + volumes: + # 登录态 cookie:容器要能写(自动重登会重写 storage_state) + - ./.auth:/app/.auth + # 账号凭据:只读挂载。文件必须先存在,见文件头「部署前置」第 2 条 + - ./account.yaml:/app/account.yaml:ro + # login.py 的持久化浏览器目录(保住设备指纹,减少重登触发风控核验) + - ./.browser-data:/app/.browser-data + # 订单 SQLite(执行事实的权威记录)+ 证据快照,丢了没法追溯下过什么单 + - ./data:/app/data + - ./logs:/app/logs + logging: + driver: json-file + options: + max-size: "50m" + max-file: "5" + # Chromium 的 namespace sandbox 在容器里可能被 seccomp/AppArmor 挡住(表现为 + # 浏览器起不来、Playwright 报 Target closed)。宿主机内核不允许非特权 user + # namespace 时,按下面两条择一放行;两条都不想放,则需要在 + # site_interact.py 的 launch(args=...) 里加 --no-sandbox(改生产代码,需另行决定)。 + # security_opt: + # - seccomp:unconfined + # cap_add: + # - SYS_ADMIN + + gateway: + # 下单任务网关:任务队列 + 状态镜像,上游业务系统在这里提交下单任务与查任务状态。 + # 正式拓扑里它在服务器侧、trading 在本地,两者靠出站长轮询联通(docs/order-gateway.md); + # 这里只是为了单机自包含跑起来,默认不启动。 + profiles: ["gateway"] + image: ${RAKUTEN_TRADING_IMAGE:-git.jerryyan.net/jp/rakuten-trading}:${RAKUTEN_TRADING_TAG:-latest} + build: + context: . + dockerfile: Dockerfile.trading + container_name: rakuten-gateway + restart: unless-stopped + init: true + command: ["python", "-m", "app.gateway.main"] + env_file: + - .env + environment: + RAKUTEN_GATEWAY_HOST: 0.0.0.0 + RAKUTEN_GATEWAY_PORT: 31109 + RAKUTEN_HEALTH_PORT: 31109 + RAKUTEN_APP_ENV: prod + # 网关不碰浏览器,跳过 Xvfb + RAKUTEN_XVFB_ENABLED: "false" + ports: + # 上游业务系统要能调到;对外暴露时请在反代上收紧来源,鉴权只有一个 Bearer token + - "${RAKUTEN_GATEWAY_BIND:-127.0.0.1}:31109:31109" + volumes: + # 任务队列 SQLite(data/gateway.db)必须持久化,丢了等于丢一批下单任务 + - ./data:/app/data + - ./logs:/app/logs + logging: + driver: json-file + options: + max-size: "50m" + max-file: "5" diff --git a/scripts/export_openapi.py b/scripts/export_openapi.py new file mode 100644 index 0000000..17ec3d3 --- /dev/null +++ b/scripts/export_openapi.py @@ -0,0 +1,322 @@ +"""把三个服务的接口合并导出成一份 openapi.json(供 Apifox / Postman 快速测试) + +仓库出三个进程、三个端口,但对外只想给一份文档,所以这里把三份 FastAPI 生成的 +spec 合成一份,并补上 FastAPI 自己表达不出来的两件事: + +1. **每个接口属于哪个服务**:给每个 operation 单独写 `servers`(OpenAPI 允许 + operation 级覆盖),导入后每条请求的 base URL 就是它真正的端口,不用手动切换。 +2. **Bearer 鉴权**:`require_bearer_token` 是自己读 Authorization 头的普通依赖, + 不是 FastAPI 的 security scheme,生成的 spec 里完全看不见。这里遍历路由的依赖 + 树识别出哪些接口真的要 token(而不是按路径猜),补上 securitySchemes + security。 + +`/health` 三个服务都有且路径相同 —— OpenAPI 的 paths 是以路径为键的,无法放三份。 +合并成一条:servers 列出三个服务,响应 schema 用 anyOf 罩住三种 HealthData, +描述里写明按 server 切换。 + +用法: + .venv/Scripts/python.exe scripts/export_openapi.py # 写回 openapi.json + .venv/Scripts/python.exe scripts/export_openapi.py --check # 只校验是否已是最新 + +tests/test_openapi_export.py 会跑 --check 的等价断言:加了新接口忘了重新导出, +测试会直接失败,避免这份文档慢慢变成过期文档。 +""" +from __future__ import annotations + +import argparse +import copy +import json +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from fastapi import FastAPI # noqa: E402 +from fastapi.routing import APIRoute # noqa: E402 + +OUTPUT_PATH = Path(__file__).resolve().parent.parent / "openapi.json" + +_SECURITY_SCHEME = "BearerAuth" + +_INFO_DESCRIPTION = """乐天 / ラクマ 抓取 + 下单交易 HTTP API(三个服务合并成一份文档)。 + +- **抓取服务** `:31107` —— 匿名无状态,可多开实例。搜索/分类/商品/店铺,含 ラクマ。 +- **交易服务(有状态端)** `:31108` —— 持账号登录态,加购与登录态管理,**只能单实例**。 +- **下单任务网关** `:31109` —— 下单任务队列与状态查询,本地 worker 长轮询领任务,**只能单实例**。 + +每个接口的 `servers` 已按所属服务单独标注,导入后不需要手动切 base URL。 +除 `/health` 外全部需要请求头 `Authorization: Bearer `。 +响应统一是 `{success, msg, data, code}` 信封,字段与错误码说明见项目 README.md。 + +本文件由 scripts/export_openapi.py 生成,不要手改。""" + + +@dataclass(frozen=True) +class Service: + """一个部署单元在文档里的身份""" + + key: str # 用于 operationId 前缀与 schema 重名时的前缀 + label: str # 展示名(tag 前缀 / Apifox 目录名) + module: str # 入口模块,取其 create_app + port: int + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.port}" + + +SERVICES = ( + Service(key="scraping", label="抓取服务", module="app.scraping.main", port=31107), + Service(key="trading", label="交易服务", module="app.trading.main", port=31108), + Service(key="gateway", label="下单网关", module="app.gateway.main", port=31109), +) + +_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace") + + +def _create_app(service: Service) -> FastAPI: + """按模块名取 create_app 并建应用(不跑 lifespan,无副作用)""" + module = __import__(service.module, fromlist=["create_app"]) + return module.create_app() + + +def _api_routes(app: FastAPI) -> list[APIRoute]: + """摊平取出所有 APIRoute + + 新版 FastAPI(0.140)的 include_router 不再把子路由摊到 app.routes 上,而是包成 + _IncludedRouter,真正的路由挂在它的 original_router.routes 上。不递归下去的话 + 一条 APIRoute 都拿不到,鉴权也就全都识别不出来。 + """ + found: list[APIRoute] = [] + + def walk(routes: list[Any]) -> None: + for route in routes: + if isinstance(route, APIRoute): + found.append(route) + continue + nested = getattr(route, "routes", None) + if nested is None: + inner = getattr(route, "original_router", None) + nested = getattr(inner, "routes", None) + if nested: + walk(list(nested)) + + walk(list(app.routes)) + return found + + +def _bearer_protected(app: FastAPI) -> set[tuple[str, str]]: + """遍历依赖树,找出真的挂了 require_bearer_token 的 (path, method) + + 不按路径规律猜:以后哪条接口加/去掉鉴权,文档要跟着自动变。 + """ + from app.shared.api import require_bearer_token + + def uses_token(dependant: Any, seen: set[int]) -> bool: + if id(dependant) in seen: + return False + seen.add(id(dependant)) + if getattr(dependant, "call", None) is require_bearer_token: + return True + return any(uses_token(sub, seen) for sub in dependant.dependencies) + + protected: set[tuple[str, str]] = set() + for route in _api_routes(app): + if uses_token(route.dependant, set()): + protected.update((route.path, method.lower()) for method in route.methods) + return protected + + +def _rewrite_refs(node: Any, rename: dict[str, str]) -> Any: + """递归把 $ref 指向的 schema 名按 rename 表替换""" + if isinstance(node, dict): + result = {} + for key, value in node.items(): + if key == "$ref" and isinstance(value, str): + name = value.rsplit("/", 1)[-1] + if value.startswith("#/components/schemas/") and name in rename: + result[key] = f"#/components/schemas/{rename[name]}" + continue + result[key] = _rewrite_refs(value, rename) + return result + if isinstance(node, list): + return [_rewrite_refs(item, rename) for item in node] + return node + + +def _merge_schemas( + merged: dict[str, Any], incoming: dict[str, Any], service: Service +) -> dict[str, str]: + """把一个服务的 schemas 并进总表,返回该服务需要的重命名表 + + 同名同内容(如 ApiResponse 信封派生出的公共模型、HTTPValidationError)直接复用; + 同名不同内容才加服务前缀——三个服务的模型确实可能撞名,但不能让后来者悄悄覆盖前者。 + """ + rename: dict[str, str] = {} + for name, schema in incoming.items(): + if name not in merged: + merged[name] = schema + continue + if merged[name] == schema: + continue + rename[name] = f"{service.key.capitalize()}{name}" + for original, renamed in rename.items(): + merged[renamed] = incoming[original] + return rename + + +def _response_schemas(operation: dict[str, Any]) -> dict[str, Any]: + """取 200 响应的 JSON schema(没有则空 dict)""" + content = operation.get("responses", {}).get("200", {}).get("content", {}) + return content.get("application/json", {}).get("schema", {}) or {} + + +def _merge_same_path(existing: dict[str, Any], incoming: dict[str, Any]) -> None: + """同路径同方法(只有 /health):并 servers、并响应 schema、拼描述""" + for server in incoming.get("servers", []): + if server not in existing.setdefault("servers", []): + existing["servers"].append(server) + + existing_schema = _response_schemas(existing) + incoming_schema = _response_schemas(incoming) + if existing_schema and incoming_schema and existing_schema != incoming_schema: + options = existing_schema.get("anyOf", [existing_schema]) + if incoming_schema not in options: + options = [*options, incoming_schema] + existing["responses"]["200"]["content"]["application/json"]["schema"] = { + "anyOf": options, + "title": "各服务的健康检查响应", + } + + incoming_description = incoming.get("description", "").strip() + if incoming_description and incoming_description not in existing.get("description", ""): + existing["description"] = ( + f"{existing.get('description', '').rstrip()}\n\n---\n\n{incoming_description}" + ) + + +def build_spec() -> dict[str, Any]: + """合并三个服务的 OpenAPI 文档""" + paths: dict[str, Any] = {} + schemas: dict[str, Any] = {} + tags: list[dict[str, str]] = [] + + for service in SERVICES: + app = _create_app(service) + spec = copy.deepcopy(app.openapi()) + protected = _bearer_protected(app) + + rename = _merge_schemas( + schemas, spec.get("components", {}).get("schemas", {}), service + ) + service_paths = _rewrite_refs(spec.get("paths", {}), rename) + + # 鉴权是从路由依赖树里认出来的,路径对不上就等于漏标——宁可构建失败, + # 也不要导出一份「看起来不需要 token」的文档 + unmatched = sorted( + f"{method.upper()} {path}" + for path, method in protected + if method not in service_paths.get(path, {}) + ) + if unmatched: + raise RuntimeError( + f"{service.key}: 这些需要鉴权的路由在 OpenAPI 里找不到对应 operation:" + f"{unmatched}(include_router 加了 prefix?)" + ) + + for path, path_item in service_paths.items(): + for method, operation in path_item.items(): + if method not in _METHODS: + continue + operation["servers"] = [{"url": service.url, "description": service.label}] + # operationId 必须全局唯一:三个服务的 /health 生成的都是 health_health_get + operation["operationId"] = f"{service.key}_{operation.get('operationId', method)}" + raw_tags = operation.get("tags") or ["default"] + operation["tags"] = [f"{service.label}/{tag}" for tag in raw_tags] + for tag in operation["tags"]: + if all(item["name"] != tag for item in tags): + tags.append({"name": tag, "description": f"{service.label}({service.url})"}) + # Apifox 目录:与 tag 一致,导入后直接按服务分组 + operation["x-apifox-folder"] = operation["tags"][0] + if (path, method) in protected: + operation["security"] = [{_SECURITY_SCHEME: []}] + + if path not in paths: + paths[path] = path_item + continue + for method, operation in path_item.items(): + if method in paths[path]: + _merge_same_path(paths[path][method], operation) + else: + paths[path][method] = operation + + return { + "openapi": "3.1.0", + "info": { + "title": "Rakuten API(抓取 / 交易 / 下单网关)", + "version": "0.1.0", + "description": _INFO_DESCRIPTION, + "x-apifox-folder": "Rakuten", + }, + "servers": [ + {"url": service.url, "description": f"{service.label} :{service.port}"} + for service in SERVICES + ], + "tags": tags, + "paths": paths, + "components": { + "schemas": schemas, + "securitySchemes": { + _SECURITY_SCHEME: { + "type": "http", + "scheme": "bearer", + "description": "值取配置项 RAKUTEN_BEARER_TOKEN;三个服务共用同一个 token", + } + }, + }, + } + + +def dump(spec: dict[str, Any]) -> str: + """固定序列化形式,便于 --check 直接比字符串""" + return json.dumps(spec, ensure_ascii=False, indent=2, sort_keys=False) + "\n" + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="导出合并后的 openapi.json") + parser.add_argument( + "--check", + action="store_true", + help="只校验 openapi.json 是否与当前代码一致,不写文件;不一致时退出码 1", + ) + parser.add_argument("--output", default=str(OUTPUT_PATH)) + args = parser.parse_args(argv) + + content = dump(build_spec()) + output = Path(args.output) + + if args.check: + current = output.read_text(encoding="utf-8") if output.exists() else "" + if current == content: + print(f"openapi.json 已是最新:{output}") + return 0 + print( + f"openapi.json 与当前代码不一致:{output}\n" + "请重新导出:.venv/Scripts/python.exe scripts/export_openapi.py", + file=sys.stderr, + ) + return 1 + + output.write_text(content, encoding="utf-8") + spec = json.loads(content) + print(f"已写入 {output}") + print(f"接口数:{sum(1 for item in spec['paths'].values() for _ in item)}(路径 {len(spec['paths'])} 条)") + for path in spec["paths"]: + methods = [m.upper() for m in spec["paths"][path] if m in _METHODS] + print(f" {','.join(methods):6} {path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_openapi_export.py b/tests/test_openapi_export.py new file mode 100644 index 0000000..95057c7 --- /dev/null +++ b/tests/test_openapi_export.py @@ -0,0 +1,105 @@ +"""openapi.json 导出测试:守住「一份文档覆盖三个服务」的合并结果 + +这份文档是外部(Apifox / Postman / 上游联调)唯一的接口来源,合并逻辑错了就会 +把人引到不存在的接口、或漏标鉴权。下面的用例全部在内存里 build_spec() 检查合并 +结果,不读仓库里的 openapi.json——那个文件是 gitignore 的生成物,CI 的全新 clone +里根本不存在,断言「文件内容 == 当前导出结果」在 CI 上必然失败。 + +因此「改了接口忘了重新导出」没有自动兜底,得手动跑: + .venv/Scripts/python.exe scripts/export_openapi.py --check +""" +from __future__ import annotations + +import importlib.util +import json +import re +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "scripts" / "export_openapi.py" + +_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace") + + +def _load_exporter(): + """按路径加载 scripts/export_openapi.py(scripts 不是包) + + 必须先塞进 sys.modules 再 exec:dataclass 解析类型注解时会去 + sys.modules[cls.__module__] 找命名空间,没登记就直接 AttributeError。 + """ + spec = importlib.util.spec_from_file_location("export_openapi", SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +@pytest.fixture(scope="module") +def exporter(): + return _load_exporter() + + +@pytest.fixture(scope="module") +def spec(exporter): + return exporter.build_spec() + + +def _operations(document: dict) -> list[tuple[str, str, dict]]: + return [ + (path, method, operation) + for path, item in document["paths"].items() + for method, operation in item.items() + if method in _METHODS + ] + + +def test_covers_all_three_services(spec): + paths = spec["paths"] + # 抓取 + assert "/api/search" in paths + assert "/api/rakuma/search" in paths + # 交易(有状态端) + assert "/api/auth/login" in paths + assert "/api/cart/add" in paths + # 网关 + assert "/api/orders" in paths + assert "/api/orders/lease" in paths + + +def test_each_operation_points_at_its_own_service(spec): + """operation 级 servers:导入后不必手动切 base URL""" + by_path = {path: operation["servers"][0]["url"] for path, _, operation in _operations(spec)} + assert by_path["/api/search"].endswith(":31107") + assert by_path["/api/cart/add"].endswith(":31108") + assert by_path["/api/orders/lease"].endswith(":31109") + # /health 三个服务都有,合成一条并列出三个 server + health_servers = {s["url"] for s in spec["paths"]["/health"]["get"]["servers"]} + assert len(health_servers) == 3 + + +def test_only_health_is_public(spec): + """除 /health 外都必须标 Bearer 鉴权——漏标会让调用方以为能匿名调""" + unprotected = [ + f"{method.upper()} {path}" + for path, method, operation in _operations(spec) + if "security" not in operation + ] + assert unprotected == ["GET /health"] + assert "BearerAuth" in spec["components"]["securitySchemes"] + + +def test_operation_ids_are_unique(spec): + """三个服务的 /health 原本都叫 health_health_get,撞了会让导入工具丢接口""" + ids = [operation["operationId"] for _, _, operation in _operations(spec)] + assert len(ids) == len(set(ids)) + + +def test_all_refs_resolve(spec): + """合并 schema 时如果重名处理错了,$ref 会指向不存在的定义""" + names = set(spec["components"]["schemas"]) + refs = set(re.findall(r"#/components/schemas/([^\"]+)", json.dumps(spec))) + assert not refs - names diff --git a/tests/test_trading_api.py b/tests/test_trading_api.py index 689b79d..9bcd794 100644 --- a/tests/test_trading_api.py +++ b/tests/test_trading_api.py @@ -24,7 +24,10 @@ class StubAuthSession: def __init__(self) -> None: self.checked: list[str] = [] self.reloaded: list[str] = [] + self.relogin_calls: list[str] = [] self.logged_in = True + # try_relogin 的结果;None 表示「登录成功并转为登录态」 + self.relogin_result: bool | None = None @property def sites(self) -> tuple[str, ...]: @@ -53,6 +56,14 @@ class StubAuthSession: self.reloaded.append(site) return 3 + async def try_relogin(self, site: str) -> bool: + """默认「登录成功」:翻成登录态并返回 True;relogin_result 可注入失败""" + self.relogin_calls.append(site) + if self.relogin_result is None: + self.logged_in = True + return True + return self.relogin_result + async def require_logged_in(self, site: str) -> None: if not self.logged_in: raise NotLoggedInError(site=site, detail="stub") @@ -168,7 +179,9 @@ def test_health_does_not_probe_the_site(client, stub): # ---- 鉴权 ---- -@pytest.mark.parametrize("path", ["/api/auth/status", "/api/auth/reload"]) +@pytest.mark.parametrize( + "path", ["/api/auth/status", "/api/auth/login", "/api/auth/reload"] +) def test_auth_endpoints_reject_missing_token(client, path): response = client.post(path, json={}) assert response.status_code == 401 @@ -213,6 +226,92 @@ def test_status_rejects_unknown_site(client): assert response.json()["code"] == 1002 +# ---- 自动登录 ---- + + +def test_login_skips_when_already_logged_in(client, stub): + """已登录时不该白起一次登录流程(起浏览器 + 打站点,代价不小)""" + response = client.post("/api/auth/login", json={}, headers=AUTH) + assert response.status_code == 200 + body = response.json() + assert body["data"]["logged_in"] is True + assert body["data"]["relogin_attempted"] == {"rakuten": False} + assert stub.relogin_calls == [] + # 结论必须来自真实探测,不能只看缓存 + assert stub.checked == ["rakuten"] + + +def test_login_triggers_relogin_when_logged_out(client, stub): + stub.logged_in = False + response = client.post("/api/auth/login", json={"site": "rakuten"}, headers=AUTH) + assert response.status_code == 200 + body = response.json() + assert body["data"]["logged_in"] is True + assert body["data"]["relogin_attempted"] == {"rakuten": True} + assert stub.relogin_calls == ["rakuten"] + # 登录后必须再探测一次确认,不能拿登录流程的自述当结论 + assert stub.checked == ["rakuten", "rakuten"] + + +def test_login_reports_failure_without_raising(client, stub): + """登录失败按 logged_in=false 正常返回,不是 5001 + + 调用方要据此决定人工接管还是换账号;抛错会把「为什么失败」压成一个错误码。 + """ + stub.logged_in = False + stub.relogin_result = False + response = client.post("/api/auth/login", json={}, headers=AUTH) + assert response.status_code == 200 + body = response.json() + assert body["success"] is True + assert body["data"]["logged_in"] is False + assert body["data"]["relogin_attempted"] == {"rakuten": True} + + +def test_login_rejects_unknown_site(client): + response = client.post("/api/auth/login", json={"site": "mercari"}, headers=AUTH) + assert response.status_code == 422 + assert response.json()["code"] == 1002 + + +# ---- 启动时自动登录(RAKUTEN_AUTO_LOGIN_ON_START)---- + + +class _FakeContainer: + def __init__(self, auth_session) -> None: + self.auth_session = auth_session + + +async def test_auto_login_on_start_skips_when_logged_in(): + from app.trading.main import auto_login_on_start + + stub = StubAuthSession() + await auto_login_on_start(_FakeContainer(stub)) + assert stub.relogin_calls == [] + + +async def test_auto_login_on_start_logs_in_when_logged_out(): + from app.trading.main import auto_login_on_start + + stub = StubAuthSession() + stub.logged_in = False + await auto_login_on_start(_FakeContainer(stub)) + assert stub.relogin_calls == ["rakuten"] + + +async def test_auto_login_on_start_swallows_errors(): + """探测抛错也不能把启动流程带崩——服务要能起来报「未登录」""" + from app.trading.main import auto_login_on_start + + class Boom(StubAuthSession): + async def check(self, site: str): + raise RuntimeError("站点不可达") + + stub = Boom() + await auto_login_on_start(_FakeContainer(stub)) + assert stub.relogin_calls == [] + + # ---- 登录态重载 ----