37 lines
979 B
Python
37 lines
979 B
Python
"""
|
|
短幂等:同一 idempotency_key 在 TTL 内不重复入队。
|
|
|
|
本文件职责:SET NX + EX;成功表示「首次」、失败表示「重复」。
|
|
禁止:用本机制代替主账写幂等;禁止无 TTL 的永久键。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from agent.redis_coord.client import RedisClient
|
|
from agent.redis_coord.keys import IDEMPOTENCY
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def try_acquire(
|
|
client: RedisClient,
|
|
*,
|
|
scope: str,
|
|
idempotency_key: str,
|
|
ttl_seconds: int = 300,
|
|
) -> bool:
|
|
"""
|
|
尝试占用短幂等键。
|
|
|
|
返回 True=首次(可入队);False=TTL 内重复。
|
|
副作用:写带过期的 Redis 键。
|
|
"""
|
|
key = client.key(IDEMPOTENCY, scope, idempotency_key)
|
|
ok = client.raw.set(key, "1", ex=ttl_seconds, nx=True)
|
|
acquired = bool(ok)
|
|
if not acquired:
|
|
logger.info("短幂等命中重复 scope=%s key=%s", scope, idempotency_key)
|
|
return acquired
|