fix: 翻译主流程失败时 raise(不再返回占位符); add_usage TTL 用 replace(day=1) 防 0 TTL

This commit is contained in:
Mavis
2026-06-07 23:58:13 +08:00
parent 501713a3e8
commit cc02d39d29
13 changed files with 568 additions and 15 deletions

View File

@@ -59,17 +59,16 @@ class TranslationService:
async def add_usage(self, chars: int) -> None:
r = get_redis()
# 用 INCRBY + EXPIRE 月初;简单做法:每次 set + 设 TTL
key = _month_key()
now = datetime.now(timezone.utc)
# 下个月第一天
if now.month == 12:
next_month = now.replace(year=now.year + 1, month=1, day=1)
else:
next_month = now.replace(month=now.month + 1, day=1, hour=0, minute=0, second=0, microsecond=0)
ttl = max(60, int((next_month - now).total_seconds()) + 86400) # +1 天 buffer
async with r.pipeline(transaction=False) as pipe:
pipe.incrby(key, chars)
# 月底过期(下下月 1 日)
now = datetime.now(timezone.utc)
if now.month == 12:
next_month = now.replace(year=now.year + 1, month=1, day=1)
else:
next_month = now.replace(month=now.month + 1, day=1)
ttl = int((next_month - now).total_seconds()) + 86400
pipe.expire(key, ttl)
await pipe.execute()
@@ -106,6 +105,7 @@ class TranslationService:
# 3) 调用
async with self._sem:
res = None
try:
res = await engine.translate(text, source=source, target=target)
except Exception as e:
@@ -113,13 +113,14 @@ class TranslationService:
logger.exception("translate failed with %s: %s", engine.name, e)
fb = self._fallback()
if fb is not None and engine is not fb:
res = await fb.translate(text, source=source, target=target)
else:
res = TranslationResult(
text=text + f"\n\n[翻译失败: {e}]",
engine="skip",
chars=chars,
)
try:
res = await fb.translate(text, source=source, target=target)
except Exception as e2:
logger.exception("fallback %s also failed: %s", fb.name, e2)
res = None
if res is None:
# 主 + fallback 都失败:抛异常,让上层标记 status=failed
raise RuntimeError(f"translation failed for {chars} chars (engine={engine.name})")
# 4) 写缓存(无论引擎)
try: