fix(garmin): 刷新出来的令牌从来没写回库,于是每次连接都重换一次
「又被限流了」的根因找到了,不是请求量,是令牌。 `_connect` 里 `refresh_oauth2()` 换来的新 OAuth2 令牌只活在进程内存里—— `save_token` 只在绑定账号时调用过一次。于是每次客户端缓存过期(15 分钟)、 每个 gunicorn worker、每次部署重启,都从库里读回**同一个已过期的令牌**, 然后再做一次真实 SSO 换令牌。而 SSO 端点是按账号限流最狠的那个,社区报告能 封 48 小时(garth #217、python-garminconnect #337)。我今天为了部署重启了 八次服务,每次都清掉缓存。 - `refresh_oauth2()` 成功后 `_persist_token()` 写回。拆出这个函数是因为它和 `save_token` 想要的正好相反:重新绑定要作废现有会话,持久化刷新结果必须 保住刚刚产出它的那个会话 - 写回时不带 garmin_email,否则 upsert 会把绑定邮箱刷成 NULL,数据同步页会 忘记绑的是哪个账号 - 刷新加进程内锁,并在拿到锁后重读一次库:另一个线程刚换过就直接用它的, 不再自己去换一次 - 五条测试盯住这个不变量,包括「冷缓存不该再换一次」(这条如果回归,就是同一 个 bug 再来一遍) 顺带把数据端点也节流了——那是另外一半问题,不是这次的病因,但一天历史要 9 次 调用,730 天全历史 6600 个请求全速打出去,不该指望佳明一直容忍: - services/garmin_throttle.py:代理包住 client,所有调用(含以后新加的)都经 同一个收口,按间隔排队并计数 - 0.5s 是查过的:garmin-data-export 默认 0.15s、garmin-connect-scraper 默认 3s、官方合作方 API 100 次/分钟(0.6s)。依据写在文件顶部 - 单次同步 1200 个请求预算,跑满就干净收尾、下次接着跑(已存的天数本来就跳过) - 运动详情每次最多补 40 条——新账号几百条,不限量就是一次性打光预算 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -999,3 +999,132 @@ class TestSyncHistory:
|
||||
r = client.get("/api/garmin/sync-history", headers=auth)
|
||||
assert r.status_code == 200
|
||||
assert r.get_json() == {"items": []}
|
||||
|
||||
|
||||
class TestRefreshedTokenIsKept:
|
||||
"""The account's repeated lockouts came from here.
|
||||
|
||||
`refresh_oauth2()` mints a token against Garmin's SSO endpoint — the one
|
||||
that limits per account and blocks for hours. The refreshed token used to
|
||||
live only in the process's memory, so every cold client cache (a 15-minute
|
||||
timeout, a second gunicorn worker, a deploy restart) re-read the same
|
||||
expired token from the database and minted another one.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _garmin(refreshes, expired_after_load=True):
|
||||
class StubOAuth2:
|
||||
def __init__(self, expired):
|
||||
self.expired = expired
|
||||
|
||||
class StubGarth:
|
||||
def __init__(self):
|
||||
self.oauth2_token = None
|
||||
self.profile = {"displayName": "Tester"}
|
||||
self.dumped = "refreshed-token"
|
||||
|
||||
def configure(self, **kwargs):
|
||||
pass
|
||||
|
||||
def loads(self, token):
|
||||
self.oauth2_token = StubOAuth2(
|
||||
expired_after_load if token == "stored-token" else False
|
||||
)
|
||||
|
||||
def refresh_oauth2(self):
|
||||
refreshes.append(1)
|
||||
self.oauth2_token = StubOAuth2(False)
|
||||
|
||||
def dumps(self):
|
||||
return self.dumped
|
||||
|
||||
class StubGarmin:
|
||||
def __init__(self, is_cn=False):
|
||||
self.garth = StubGarth()
|
||||
self.display_name = None
|
||||
|
||||
return StubGarmin
|
||||
|
||||
def test_the_refreshed_token_is_written_back(self, db, user, monkeypatch):
|
||||
refreshes = []
|
||||
monkeypatch.setattr(garmin_svc, "_import_garmin",
|
||||
lambda: self._garmin(refreshes))
|
||||
garmin_svc.save_token(user["id"], "stored-token", "a@example.com")
|
||||
|
||||
garmin_svc._connect({}, user["id"])
|
||||
|
||||
assert refreshes == [1]
|
||||
assert garmin_svc.load_token(user["id"]) == "refreshed-token", (
|
||||
"a refresh that is not persisted makes the next connect mint "
|
||||
"another token against the endpoint that blocks accounts"
|
||||
)
|
||||
|
||||
def test_persisting_a_refresh_keeps_the_bound_email(self, db, user, monkeypatch):
|
||||
refreshes = []
|
||||
monkeypatch.setattr(garmin_svc, "_import_garmin",
|
||||
lambda: self._garmin(refreshes))
|
||||
garmin_svc.save_token(user["id"], "stored-token", "a@example.com")
|
||||
garmin_svc.forget_client(user["id"])
|
||||
|
||||
garmin_svc._connect({}, user["id"])
|
||||
|
||||
assert garmin_svc.get_remembered_email(user["id"]) == "a@example.com", (
|
||||
"the 数据同步 page shows this; a refresh must not blank it"
|
||||
)
|
||||
|
||||
def test_a_cold_cache_does_not_refresh_again(self, db, user, monkeypatch):
|
||||
"""The whole point: the second connect reads a *valid* stored token."""
|
||||
refreshes = []
|
||||
monkeypatch.setattr(garmin_svc, "_import_garmin",
|
||||
lambda: self._garmin(refreshes))
|
||||
garmin_svc.save_token(user["id"], "stored-token", "a@example.com")
|
||||
|
||||
garmin_svc._connect({}, user["id"])
|
||||
garmin_svc.forget_client(user["id"]) # as a restart or TTL would
|
||||
garmin_svc._connect({}, user["id"])
|
||||
|
||||
assert refreshes == [1], f"minted {len(refreshes)} SSO tokens, expected 1"
|
||||
|
||||
def test_persisting_the_refresh_does_not_drop_the_live_session(
|
||||
self, db, user, monkeypatch
|
||||
):
|
||||
"""`save_token` invalidates the cached client; the refresh path must
|
||||
not, or every connect would throw its own session away."""
|
||||
refreshes = []
|
||||
monkeypatch.setattr(garmin_svc, "_import_garmin",
|
||||
lambda: self._garmin(refreshes))
|
||||
garmin_svc.save_token(user["id"], "stored-token", "a@example.com")
|
||||
|
||||
first = garmin_svc._connect({}, user["id"])
|
||||
second = garmin_svc._connect({}, user["id"])
|
||||
assert second is first, "the session was cached, not rebuilt"
|
||||
|
||||
def test_a_rate_limited_refresh_still_surfaces_as_rate_limited(
|
||||
self, db, user, monkeypatch
|
||||
):
|
||||
class StubGarth:
|
||||
oauth2_token = None
|
||||
profile = {"displayName": "Tester"}
|
||||
|
||||
def configure(self, **kwargs):
|
||||
pass
|
||||
|
||||
def loads(self, token):
|
||||
pass
|
||||
|
||||
def refresh_oauth2(self):
|
||||
raise Exception("429 Client Error: Too Many Requests")
|
||||
|
||||
def dumps(self):
|
||||
return "unused"
|
||||
|
||||
class StubGarmin:
|
||||
def __init__(self, is_cn=False):
|
||||
self.garth = StubGarth()
|
||||
|
||||
monkeypatch.setattr(garmin_svc, "_import_garmin", lambda: StubGarmin)
|
||||
garmin_svc.save_token(user["id"], "stored-token", "a@example.com")
|
||||
|
||||
with pytest.raises(garmin_svc.RateLimited):
|
||||
garmin_svc._connect({}, user["id"])
|
||||
assert garmin_svc.rate_limited_until(user["id"]) is not None
|
||||
|
||||
Reference in New Issue
Block a user