feat(observability): 抓取去掉首页预热,交易补齐链路埋点

两个问题一起处理,都与「出站请求与可观测性」有关。

## 抓取:正常路径不再多打一次首页

site_session 原先每条通道每 30 分钟打一次 www.rakuten.co.jp/ 做预热,而且预热
返回非 2xx 时 warmed_at 不置位——那种情况下每个请求前都会再打一次首页。

Akamai 的 cookie 随任意页面响应下发,目标页自己就会带回来,专门先打一次首页除了
多一个出站请求(以及多一次被风控计数的机会)之外没有额外收益:首个请求无论打哪个
URL 都是冷的 ~11s,之后都复用 cookie。

改为 cookie 由目标页响应建立(_note_cookies)、超 TTL 主动清空
(_drop_expired_cookies)。首页只保留在失败修复路径上(_rewarm_on_home):目标页
已经吃了挑战页时,拿首页换一套干净 cookie 比继续撞同一个 URL 更安全。happy path
的出站请求数 2 → 1。

_note_cookies 刻意不在每次响应时刷新时刻:TTL 要从「这套 cookie 第一次出现」算起,
每次都刷新会让一套 cookie 被无限续命,反而绕过了 session_ttl_seconds 的本意。

profile_status() 的 warmed 字段名保留(上游健康检查看板在用),语义改为「当前有
可复用的 Akamai cookie」,不再代表「已专门预热过首页」。

## 交易:此前没有任何有意义的链路数据

根因是 trading 的实际工作两类自动埋点都覆盖不到:站点交互走 Playwright(不经
httpx),worker 主循环是后台 asyncio 任务(没有 HTTP 入口,因此没有根 span)。
于是发给网关的每次 httpx 调用各自成为孤立 trace——观测后台上只剩一堆请求记录。

新增手工埋点:

- order.task:一笔下单的根 span,一个 task_id 一条 trace,带 order.route
  (execute / recovery / already_finished)与终态 order.terminal_status
- order.step.*:清车 → 加购 → 校验 → 确认 → 提交 → 付款,每步一个子 span,
  带 order.evidence_ref,可从 span 直接定位落盘证据
- site.*:12 个 Playwright 交互方法(用 traced 装饰器而非 with 块——这些方法的
  函数体本就很长,再加一层缩进不利于阅读)
- account_query:只读查询单的根 span,带 query.outcome

空转的长轮询(30 秒一次、绝大多数返回空)用 suppressed() 屏蔽:量大且没有信息量,
把观测后台刷满的正是它们。领到任务后的网关调用都在任务根 span 底下,不受影响。

闸门 / 风控拦截会被 _execute_with_renewal 吞掉转 needs_human,异常冒不到根 span,
被拦下的单在 trace 里跟成功下单一模一样。加 _execute_recording_errors 一层统一
记录,比每个 except 分支各写一遍省事,也不会漏掉后续新增的分支。

_report_safe 写 span 属性前判断 is_recording():付款后监控是 create_task 起的,
asyncio 在创建时就把 context 复制了进去,等它真正跑起来根 span 早已结束——
get_current_span() 拿到的仍是那个已结束的 span(不是 INVALID_SPAN),写属性会打
"Setting attribute on ended span"。当前监控路径不传 terminal_status 走不到那里,
这道判断是防以后。

## 顺带修掉:instrument_app 从未生效

instrument_app 用 _provider is None 做前置判断,但三个服务都在模块导入时执行
app = create_app(),而 setup_telemetry 要等 lifespan 才跑——那时 _provider 还是
None,照着判断直接 return。**FastAPI 从来没被打桩过,三个服务一条 server span
都没有。**

实测确认两件事:导入期打桩能出 span,lifespan 内打桩出不来(instrument_app 是加
中间件,应用开始服务后加进去不生效);provider 后设也不影响 ProxyTracer 委托到
真实 provider。所以只能在导入期装,判断条件改为 otel_enabled。

app/gateway/main.py 此前完全没接 telemetry,worker 出站请求带过来的 traceparent
没人接上,一条下单链路在网关这里断掉,只看得到 worker 侧那半截。补上
setup_telemetry(service_name="rakuten-gateway") 与 instrument_app / shutdown。

## 验证

新增 8 个用例:首页零请求、cookie 复用与过期清空、失败后用首页换 cookie、一任务
一 trace 的父子结构、闸门失败标 ERROR、空转不埋点,以及 instrument_app 调用顺序
的回归测试。全量 526 passed。

Playwright 那些 site.* 埋点只做了静态验证(测试用桩替换站点方法),没有跑真实
浏览器下单确认 span 真的落地。

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-08-28 14:56:49 +08:00
co-authored by Claude Opus 5
parent bba45d7f7c
commit 3c7618a1d6
12 changed files with 727 additions and 113 deletions
+78 -45
View File
@@ -8,7 +8,13 @@
画像(详情页只有手机 UA 才返回带 __INITIAL_STATE__ 的统一模板)。两条通道
各自持有独立 cookie 罐,避免把 PC 指纹拿到的 cookie 混用到手机请求上。
抓取失败时的升级路径:重新预热 → 浏览器兜底取 cookie → 放弃。
**不预热首页**:Akamai 的 cookie 是随任意一个页面响应下发的,目标页自己就会带回
来,专门先打一次 `www.rakuten.co.jp/` 除了多一个出站请求(以及多一次被风控计数
的机会)之外没有额外收益——首个请求无论打哪个 URL 都是冷的 ~11s,之后都复用
cookie。首页只在**失败修复**路径上使用:目标页已经被挑战时,拿首页换一套干净
cookie 比继续拿目标页去撞更安全(见 `_rewarm_on_home`)。
抓取失败时的升级路径:换 cookie(首页重新预热)→ 浏览器兜底取 cookie → 放弃。
"""
from __future__ import annotations
@@ -62,12 +68,18 @@ class _Profile:
mobile: bool
client: httpx.AsyncClient
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
warmed_at: float = 0.0
# Akamai cookie 罐的建立时刻(monotonic)。0 表示当前没有可复用的 cookie。
# 超过 session_ttl_seconds 就主动清空:拿着过期 cookie 去撞反而更容易被挑战。
cookies_at: float = 0.0
@property
def cookie_names(self) -> set[str]:
return {cookie.name for cookie in self.client.cookies.jar}
@property
def akamai_cookies(self) -> set[str]:
return self.cookie_names & set(site.AKAMAI_COOKIE_NAMES)
class SiteSession:
"""乐天站点抓取会话,管理 cookie 预热、并发限流与失败升级"""
@@ -115,13 +127,17 @@ class SiteSession:
# ---- 状态 ----
def profile_status(self) -> dict[str, dict[str, Any]]:
"""各通道的预热状态,供健康检查展示"""
"""各通道的 cookie 状态,供健康检查展示
`warmed` 保留原字段名(上游健康检查看板在用),语义是「当前有可复用的
Akamai cookie」——不再代表「已专门预热过首页」,因为正常路径不打首页了。
"""
now = time.monotonic()
return {
name: {
"warmed": profile.warmed_at > 0,
"age_seconds": round(now - profile.warmed_at, 1) if profile.warmed_at else None,
"cookies": sorted(profile.cookie_names & set(site.AKAMAI_COOKIE_NAMES)),
"warmed": profile.cookies_at > 0,
"age_seconds": round(now - profile.cookies_at, 1) if profile.cookies_at else None,
"cookies": sorted(profile.akamai_cookies),
}
for name, profile in self._profiles.items()
}
@@ -142,7 +158,8 @@ class SiteSession:
) -> FetchedPage:
"""抓取页面,返回 HTML 与最终落地地址
失败时按 重新预热 → 浏览器兜底 的顺序逐级升级重试。
直接打目标页(不先访问首页),失败时按 换 cookie → 浏览器兜底 的顺序
逐级升级重试。
Args:
validator: 页面校验器,默认要求页面含 __INITIAL_STATE__。跨站抓取时
@@ -181,7 +198,8 @@ class SiteSession:
try:
for attempt in range(1, max_attempts + 1):
span.set_attribute("scrape.attempts", attempt)
await self._ensure_warm(profile)
# 过期 cookie 主动丢掉:带着它去撞比裸请求更容易吃挑战页
await self._drop_expired_cookies(profile)
try:
response = await profile.client.get(url)
except httpx.HTTPError as exc:
@@ -192,6 +210,10 @@ class SiteSession:
)
continue
# 任何响应都可能带 set-cookie(Akamai 不保证每次下发),拿到就
# 记下时刻,后续请求复用到 TTL 为止。
self._note_cookies(profile)
if response.status_code == 404:
err = ItemNotFoundError(f"Page not found: {url}")
span.record_exception(err)
@@ -223,9 +245,11 @@ class SiteSession:
if attempt >= max_attempts:
break
# 第一次失败先便宜地换一套 cookie;仍失败才动用浏览器
# 第一次失败先便宜地换一套 cookie(丢掉旧的,用首页换新的);
# 仍失败才动用浏览器
if attempt == 1:
await self._invalidate(profile)
await self._rewarm_on_home(profile)
span.set_attribute("scrape.rewarmed_on_home", True)
else:
page = await self._escalate_to_browser(profile, url, validate)
if page is not None:
@@ -265,44 +289,53 @@ class SiteSession:
def _is_server_error(reason: str) -> bool:
return reason.startswith("upstream status") or reason.startswith("httpx") or "Error:" in reason
async def _ensure_warm(self, profile: _Profile) -> None:
"""确保通道有一次新鲜的首页预热;过期时重新访问首页"""
if self._is_warm(profile):
def _note_cookies(self, profile: _Profile) -> None:
"""目标页响应带回 Akamai cookie 时记下时刻,作为 TTL 起点
已经在计时的不重置:TTL 要从「这套 cookie 第一次出现」算起,每次响应都
刷新会让一套 cookie 被无限续命,反而绕过了 session_ttl_seconds 的本意。
"""
if profile.cookies_at:
return
if profile.akamai_cookies:
profile.cookies_at = time.monotonic()
async with profile.lock:
if self._is_warm(profile):
return
try:
response = await profile.client.get(self._settings.home_url)
# Akamai 不保证每次都下发 cookie;首页探测成功本身就是可复用的
# 预热结果,cookie 只用于观测和失败升级时的回灌。
if response.status_code < 400:
profile.warmed_at = time.monotonic()
logger.info(
"会话预热完成:profile=%s status=%s cookies=%s",
profile.name,
response.status_code,
sorted(profile.cookie_names & set(site.AKAMAI_COOKIE_NAMES)),
)
except httpx.HTTPError as exc:
# 预热失败不阻断本次抓取:直连目标页仍可能成功,只是慢
logger.warning("会话预热失败:profile=%s err=%s", profile.name, exc)
profile.warmed_at = 0.0
def _is_warm(self, profile: _Profile) -> bool:
if not profile.warmed_at:
return False
if time.monotonic() - profile.warmed_at > self._settings.session_ttl_seconds:
return False
return True
async def _invalidate(self, profile: _Profile) -> None:
"""清空通道 cookie 并强制下次重新预热"""
async def _drop_expired_cookies(self, profile: _Profile) -> None:
"""cookie 罐超过 TTL 时清空,让下一次请求裸奔换一套新的"""
if not profile.cookies_at:
return
if time.monotonic() - profile.cookies_at <= self._settings.session_ttl_seconds:
return
async with profile.lock:
profile.client.cookies.clear()
profile.warmed_at = 0.0
logger.info("已清空会话 cookie,将重新预热:profile=%s", profile.name)
profile.cookies_at = 0.0
logger.info("会话 cookie 已过期,已清空:profile=%s", profile.name)
async def _rewarm_on_home(self, profile: _Profile) -> None:
"""首次失败后的修复:丢掉旧 cookie,用首页换一套新的
这是首页 URL 唯一的用途。目标页已经吃了挑战页,继续拿同一个 URL 去撞
只会把挑战坐实;首页是站点最"无害"的入口,换 cookie 的成功率更高。
失败不阻断本次抓取(下一次 attempt 会裸请求目标页,只是慢),所以这里
只记日志。
"""
async with profile.lock:
profile.client.cookies.clear()
profile.cookies_at = 0.0
try:
response = await profile.client.get(self._settings.home_url)
except httpx.HTTPError as exc:
logger.warning("首页换 cookie 失败:profile=%s err=%s", profile.name, exc)
return
if profile.akamai_cookies:
profile.cookies_at = time.monotonic()
logger.info(
"已用首页换一套新 cookie:profile=%s status=%s cookies=%s",
profile.name,
response.status_code,
sorted(profile.akamai_cookies),
)
async def _escalate_to_browser(
self, profile: _Profile, url: str, validate: PageValidator
@@ -332,7 +365,7 @@ class SiteSession:
domain=cookie.get("domain") or "",
path=cookie.get("path") or "/",
)
profile.warmed_at = time.monotonic()
profile.cookies_at = time.monotonic()
# 浏览器不回报最终 URL,这里以请求地址为准;跨站跳转场景下 HTTP 通道已先行
# 报错,走不到这一步。